为BindingListView 启用LINQ
Andrew Davies在sourceforge上创建了一个名为BindingListView
的优秀小类,它基本上允许您将集合绑定到DataGridView
同时支持排序和过滤。 将DataGridView
绑定到普通List
不支持排序和过滤,因为List
没有实现正确的接口。
该类工作得很好,解决了我的UI问题。 但是,如果我可以使用LINQ迭代集合,那将是非常棒的,但我只是不确定如何设置它。 源代码可以在这里下载。 谁能帮我吗?
因为BindingListView
项目使用.NET Framework v2.0并且早于LINQ,所以它不会公开IEnumerable
供您查询。 由于它确实实现了非通用的IEnumerable
和非genericsIList
,因此您可以使用Enumerable.Cast
将集合转换为适合与LINQ一起使用的forms。 但是,这种方法没有用,因为AggregateBindingListView
返回的IEnumerable
是一个类型为KeyValuePair
的内部数据结构。
要升级此项目以方便LINQ使用,最简单的方法可能是在AggregateBindingListView
上实现IEnumerable
AggregateBindingListView
。 首先将它添加到类的声明中:
public class AggregateBindingListView : Component, IBindingListView, IList, IRaiseItemChangedEvents, ICancelAddNew, ITypedList, IEnumerable
然后在类定义的末尾实现它:
#region IEnumerable Members IEnumerator IEnumerable .GetEnumerator() { for (int i = 0; i < _sourceIndices.Count; i++) yield return _sourceIndices[i].Key.Item.Object; } #endregion
现在你可以直接在BindingListView
实例上使用LINQ,如下所示:
// Create a view of the items itemsView = new BindingListView- (feed.Items); var descriptions = itemsView.Select(t => t.Description);
请记住将所有项目从.NET Framework v2.0升级到.NET Framework 4 Client Profile并using System.Linq;
添加using System.Linq;
为了使其适用于您当前的项目。
好的,这就是我得到的:这是我的扩展方法:
public static class BindingViewListExtensions { public static void Where(this BindingListView list, Func function) { // I am not sure I like this, but we know it is a List var lists = list.DataSource as List ; foreach (var item in lists.Where (function)) { Console.WriteLine("I got item {0}", item); } }
}
然后我用它像:
List source = new List () { "One", "Two", "Thre" }; BindingListView binding = new BindingListView (source); binding.Where (xx => xx == "One");
我想扩展方法中的哪个位置可以返回找到的项目。
上述就是C#学习教程:为BindingListView 启用LINQ分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1003358.html