为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, int>的内部数据结构。

要升级此项目以方便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"); 

我想扩展方法中的哪个位置可以返回找到的项目。