2012-07-17 67 views
1

我有一个GridView,过滤和分页(一次10个)绑定到Linqdatasource。所有这些工作。迭代由Linqdatasource返回的对象

但是,如何获取所有在LinqDataSource中检索到的所有数据的Ids,它已完成对所有行的检索?

我有这样的方法,并且e.Result是包含清单此网格

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); 
     } 
    } 
} 

我的错误是遍历一个对象的对象数据类型,这可怎么办呢?

+0

什么样的名单呢e.Result包含哪些内容?如果e.Result是一个对象,则必须将其转换为适当的列表类型,以便应用索引 – 2012-07-17 18:37:49

+1

,并且还缺少括号:Foo foo =(Foo)(e.Result [idx]); – 2012-07-17 18:39:29

回答

1

你可以这样做:

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); 
     } 
    } 
} 

或者

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); 
     } 
    } 
} 

如果您选择的是筛选视图的结果,e.Result将是匿名类型的IEnumerable,所以获取信息很可能需要使用IQueryable和viewmodel对象。

1

e.Resultobject,所以你需要将其转换为一个列表类型,能够应用索引:

Foo foo = ((List<Foo>)(e.Result))[idx]; 
+0

e.Result可能是一个Enumerable,因此使用.ToList()来确保您实际上可以获取List是安全的。 – 2012-07-17 18:46:34

+0

我同意你的意见 – 2012-07-17 18:48:05