当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在C#中将IEnumerable<T>转换为List<T>?》经验,为你挑选了2个好方法。

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

简化代码:

Dictionary dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();

我认为这会工作,但实际上它会抛出一个System.InvalidOperationException:

ID为'myListView'的ListView必须具有实现ICollection的数据源,或者如果AllowPaging为true,则可以执行数据源分页.

为了使它工作,我不得不采取以下措施:

Dictionary dict = GetAllRecords();
List searchResults = new List();

var matches = dict.Values.Where(rec => rec.Name == "foo");
foreach (Record rec in matches)
    searchResults.Add(rec);

myListView.DataSource = searchResults;
myListView.DataBind();

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

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



1> Matt Hamilto..:

试试这个:

var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();

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



2> Keith..:

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

myListView.DataSource = (
    from rec in GetAllRecords().Values
    where rec.Name == "foo"
    select rec ).ToList();
myListView.DataBind();

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

推荐阅读
殉情放开那只小兔子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有