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

时间:2020-03-05 18:44:14  来源:igfitidea点击:

我正在使用LINQ查询通用字典,然后将结果用作ListView(WebForms)的数据源。

简化代码:

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

我以为那可以,但是实际上它抛出了System.InvalidOperationException:

ListView with id 'myListView' must
  have a data source that either
  implements ICollection or can perform
  data source paging if AllowPaging is
  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();

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

回答

myListView.DataSource = (List<Record>) dict.Values.Where(rec => rec.Name == "foo");

回答

我们也可以尝试:

var matches = new List<Record>(dict.Values.Where(rec => rec.Name == "foo"));

基本上,通用集合很难直接进行转换,因此,除了创建一个新对象外,我们别无选择。

回答

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

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

不使用钥匙为什么要得到字典?我们要为此付出代价。