Enable LINQ for BindingListView <T>
Andrew Davies created a great class on sourceforge called BindingListView<T>, which essentially allows you to bind collections to DataGridView, supporting sorting and filtering. Binding a DataGridViewto normal List<T>does not support sorting and filtering, since the corresponding interfaces are not implemented List<T>.
The class works great and solved the problems with the user interface. However, it would be great if I could iterate through the collection using LINQ, but I just don't know how to set it up for this. Source code can be downloaded here . Can anyone help me out?
Since the project BindingListView<T>uses the .NET Framework v2.0 and precedes LINQ, it does not expose IEnumerable<T>for the request. Since it uses neither generic IEnumerablenor generic IList, you can use Enumerable.Cast<TResult>to convert the collection into a form suitable for use with LINQ. However, this approach is not so useful because IEnumerable, returned AggregateBindingListView<T>, is an internal data structure with a type KeyValuePair<ListItemPair<T>, int>.
To upgrade this project for convenient use with LINQ, the easiest approach might be to implement IEnumerable<T>on AggregateBindingListView<T>. First add it to the class declaration:
public class AggregateBindingListView<T> : Component, IBindingListView, IList, IRaiseItemChangedEvents, ICancelAddNew, ITypedList, IEnumerable<T>
and then implement it at the end of the class definition:
#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
LINQ BindingListView<T> :
// Create a view of the items
itemsView = new BindingListView<Item>(feed.Items);
var descriptions = itemsView.Select(t => t.Description);
.NET Framework v2.0 .NET Framework 4 Client Profile using System.Linq;, .
, : :
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");
, .