如何在C#中将IEnumerable <T>转换为List <T>?

Chr*_*lid 17 c# linq generics listview

我使用LINQ查询泛型字典,然后使用结果作为我的ListView(WebForms)的数据源.

简化代码:

Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();
Run Code Online (Sandbox Code Playgroud)

我认为这会工作,但实际上它会抛出一个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();
Run Code Online (Sandbox Code Playgroud)

在第一个例子中是否有一个小问题使它工作?

(不知道该使用什么作为这个问题的标题,随意编辑更合适的东西)

Mat*_*ton 29

试试这个:

var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
Run Code Online (Sandbox Code Playgroud)

请注意,这实际上将从原始值集合中创建新列表,因此对字典的任何更改都不会自动反映在绑定控件中.


Kei*_*ith 9

我倾向于使用新的Linq语法:

myListView.DataSource = (
    from rec in GetAllRecords().Values
    where rec.Name == "foo"
    select rec ).ToList();
myListView.DataBind();
Run Code Online (Sandbox Code Playgroud)

当你不使用密钥时,为什么要收到字典?你付出了这笔费用.