Iterating over objects returned by Linqdatasource

2019-08-03 08:20发布

问题:

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?

回答1:

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.



回答2:

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];