Enabling LINQ for BindingListView

前端 未结 2 1425
清歌不尽
清歌不尽 2020-12-29 16:25

Andrew Davies created an excellent little class on sourceforge called BindingListView which essentially allows you to bind a collection to a Data

2条回答
  •  春和景丽
    2020-12-29 16:33

    Because the BindingListView project uses .NET Framework v2.0 and predates LINQ, it doesn't expose an IEnumerable for you to query on. Since it does implement non-generic IEnumerable and non-generic IList, you can use Enumerable.Cast to convert the collection into a form suitable for use with LINQ. However, this approach isn't that helpful because the IEnumerable that AggregateBindingListView returns is an internal data structure with type KeyValuePair, int>.

    To upgrade this project for convenient use with LINQ, the simplest approach might be to implement IEnumerable on AggregateBindingListView. First add it to the declaration of the class:

    public class AggregateBindingListView : Component, IBindingListView, IList, IRaiseItemChangedEvents, ICancelAddNew, ITypedList, IEnumerable
    

    and then implement it at the end of the class definition:

    #region IEnumerable Members
    
    IEnumerator IEnumerable.GetEnumerator()
    {
        for (int i = 0; i < _sourceIndices.Count; i++)
            yield return _sourceIndices[i].Key.Item.Object;
    
    }
    
    #endregion
    

    and now you can use LINQ directly on a BindingListView instance like this:

    // Create a view of the items
    itemsView = new BindingListView(feed.Items);
    var descriptions = itemsView.Select(t => t.Description);
    

    Remember to upgrade all the projects from .NET Framework v2.0 to .NET Framework 4 Client Profile and add using System.Linq; in order for this to work with your current project.

提交回复
热议问题