[英]In C#, how can I convert my array from IEnumerable<IMyInterface> to IEnumerable<T>?
[英]How can I convert IEnumerable<T> to List<T> in C#?
我使用LINQ查詢泛型字典,然后使用結果作為我的ListView(WebForms)的數據源。
簡化代碼:
Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();
我認為這會工作,但實際上它會拋出一個System.InvalidOperationException :
ID為'myListView'的ListView必須具有實現ICollection的數據源,或者如果AllowPaging為true,則可以執行數據源分頁。
為了使它工作,我不得不采取以下措施:
Dictionary<Guid, Record> dict = GetAllRecords();
List<Record> searchResults = new List<Record>();
var matches = dict.Values.Where(rec => rec.Name == "foo");
foreach (Record rec in matches)
searchResults.Add(rec);
myListView.DataSource = searchResults;
myListView.DataBind();
在第一個例子中是否有一個小問題使它工作?
(不知道該使用什么作為這個問題的標題,隨意編輯更合適的東西)
試試這個:
var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
請注意,這實際上將從原始值集合中創建新列表,因此對字典的任何更改都不會自動反映在綁定控件中。
我傾向於使用新的Linq語法:
myListView.DataSource = (
from rec in GetAllRecords().Values
where rec.Name == "foo"
select rec ).ToList();
myListView.DataBind();
當你不使用密鑰時,為什么要收到字典? 你付出了這筆費用。
您也可以嘗試:
var matches = new List<Record>(dict.Values.Where(rec => rec.Name == "foo"));
基本上通用集合很難直接投射,所以你真的別無選擇,只能創建一個新對象。
myListView.DataSource = (List<Record>) dict.Values.Where(rec => rec.Name == "foo");
只是添加知識,下一句話不能從de db中恢復任何數據。 只創建查詢(因為它是iqueryable類型)。 要啟動此查詢,您必須在末尾添加.ToList()或.First()。
dict.Values.Where(rec => rec.Name == "foo")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.