Iterating over objects returned by Linqdatasource

2019-08-03 08:00发布

I have a GridView, with filtering and pagination (10 at a time), bound to a Linqdatasource. All this works.

But how can I get the Ids of all the data retrieved in the LinqDataSource after it has finished retrieval of all rows?

I have this method, and e.Result is an object data type containing List for this grid

protected void LinqDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)  // event fires after data retrieval complete.
{
    List<int> ids = new List<int>();
    if (e.TotalRowCount > 0)
    {
        for (int idx = 0; idx < e.TotalRowCount; idx++)
        {
            Foo foo = (Foo)(e.Result[idx]);  // error cannot apply indexing to expression of type object
            ids.Add(foo.Id);
        }
    }
}

My error is iterating over an object, how can this be done?

2条回答
Melony?
2楼-- · 2019-08-03 08:21

e.Result is an object, so you need to cast it to a List type to be able to apply indexing:

Foo foo = ((List<Foo>)(e.Result))[idx];
查看更多
做自己的国王
3楼-- · 2019-08-03 08:30

You can either do:

protected void LinqDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)  // event fires after data retrieval complete.
{
    List<int> ids = new List<int>();
    if (e.TotalRowCount > 0)
    {
        List<Foo> fooList = ((IEnumerable)e.Result).ToList();
        for (int idx = 0; idx < fooList.Count; idx++)
        {
            Foo foo = fooList[idx];
            ids.Add(foo.Id);
        }
    }
}

Or

protected void LinqDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)  // event fires after data retrieval complete.
{
    List<int> ids = new List<int>();
    if (e.TotalRowCount > 0)
    {
        foreach(Foo foo in (IEnumerable)e.Result)
        {
            ids.Add(foo.Id);
        }
    }
}

If your Selected is a result of a filtered view, e.Result will be an IEnumerable of anonymous type, so getting the information will most likely require using an IQueryable and a viewmodel object.

查看更多
登录 后发表回答