Andrew Davies在sourceforge上创建了一个名为BindingListView<T>的优秀小类,它本质上允许您将集合绑定到DataGridView,同时支持排序和过滤。将DataGridView绑定到普通List<T>不支持排序和过滤,因为List<T>没有实现正确的接口。
这个类工作得很好,解决了我的UI问题。然而,如果我可以使用LINQ遍历集合,那就太棒了,但我只是不确定如何设置它来做到这一点。源代码可以从here下载。有人能帮我吗?
发布于 2011-06-07 03:26:40
因为BindingListView<T>项目使用LINQFrameworkv2.0并且早于.NET,所以它不会公开IEnumerable<T>供您查询。由于它确实实现了非泛型IEnumerable和非泛型IList,因此可以使用Enumerable.Cast<TResult>将集合转换为适合与LINQ一起使用的形式。但是,这种方法没有太大帮助,因为AggregateBindingListView<T>返回的IEnumerable是一个类型为KeyValuePair<ListItemPair<T>, int>的内部数据结构。
要升级此项目以方便使用LINQ,最简单的方法可能是在AggregateBindingListView<T>上实现IEnumerable<T>。首先将其添加到类的声明中:
public class AggregateBindingListView<T> : Component, IBindingListView, IList, IRaiseItemChangedEvents, ICancelAddNew, ITypedList, IEnumerable<T>然后在类定义的末尾实现它:
#region IEnumerable<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
for (int i = 0; i < _sourceIndices.Count; i++)
yield return _sourceIndices[i].Key.Item.Object;
}
#endregion现在,您可以直接在BindingListView<T>实例上使用LINQ,如下所示:
// Create a view of the items
itemsView = new BindingListView<Item>(feed.Items);
var descriptions = itemsView.Select(t => t.Description);请记住将所有项目从.NET Frameworkv2.0升级到.NET Framework4 Client Profile并添加using System.Linq;,以便与当前项目一起工作。
发布于 2011-06-07 03:28:08
好的,这就是我得到的:这是我的扩展方法:
public static class BindingViewListExtensions
{
public static void Where<T>(this BindingListView<T> list, Func<T, bool> function)
{
// I am not sure I like this, but we know it is a List<T>
var lists = list.DataSource as List<T>;
foreach (var item in lists.Where<T>(function))
{
Console.WriteLine("I got item {0}", item);
}
}}
然后我像这样使用它:
List<string> source = new List<string>() { "One", "Two", "Thre" };
BindingListView<string> binding = new BindingListView<string>(source);
binding.Where<string>(xx => xx == "One");我猜在扩展方法中的哪里可以返回找到的项。
https://stackoverflow.com/questions/6256559
复制相似问题