我如何转换IEnumerable的< T>列出< T>在C#中? [英] How can I convert IEnumerable<T> to List<T> in C#?

查看:195
本文介绍了我如何转换IEnumerable的< T>列出< T>在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms).

简体code:

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

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

ListView控件ID为myListView必须
  有一个数据源,要么
  实现ICollection的或可以执行
  数据源分页如果AllowPaging为
  真实的。

ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true.

为了得到它的工作我不得不求助于以下内容:

In order to get it working I have had to resort to the following:

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();

有没有在第一个例子小疑难杂症,使工作?

Is there a small gotcha in the first example to make it work?

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

(Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)

推荐答案

试试这个:

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

要知道,这基本上将创建一个从原始值集合一个新的列表,所以你的字典中的任何更改将不会自动在你的绑定控件的体现。

Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.

这篇关于我如何转换IEnumerable的&LT; T&GT;列出&LT; T&GT;在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆