2012-07-17 53 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

相關問題