简体   繁体   中英

Using LINQ on Observable Collection without losing Event subscriptions C#

I'm trying to use LINQ to sort a ObservableCollection, the problem is the LINQ's methods return a IOrderedEnumerable and there's not method to convert that type directly to ObservableCollection. After searching for a while I discovered a way do to this by using a constructor from the ObservableCollection class to create a new one using the IOrderedEnumerable:

MyObservableCollection = new ObservableCollection<T>(someIOrderedEnumerable);

However this does not solve my problem because by using this constructor the previous EventHandler is erased so I lose the references to all methods previously subscribed to the CollectionChanged event and subscribing those methods again is not possible.

Currently what I'm doing is clearing the Observable Collection and then adding the objects that were returned by the LINQ method one by one to the Observable Collection, the problem is doing this fires the CollectionChanged event many times whenever I use LINQ to order it:

var iOrderedEnumerable = MyObservableCollection.SomeLINQMethod();
MyObservableCollection.Clear();
var pivotList = iOrderedEnumerable.ToList();
for (int i = 0; i < pivotList.Count; i++)
  {
      MyObservableCollection.Add(pivotList[i]);
  }

Main question is: How do I order a Observable Collection without losing the CollectionChanged event's subscriptions?

I thought about storing the EventHandler and re-assign it after creating the new sorted Observable Collection, but haven't been able to implement this yet.

Edit1: After tinkering for a while I figured a solution for LINQ methods that only sort collections, instead of clearing the Observable Collection and then add one by one i simply set the values instead(which does not fire the CollectionChanged Event):

var iOrderedEnumerable = MyObservableCollection.SomeLINQMethod();
var pivotList = iOrderedEnumerable.ToList();
for (int i = 0; i < pivotList.Count; i++)
    {
        MyObservableCollection[i] = pivotList[i];
    }

My library ObservableComputations can help you. Using that library your code will look like following:

    ObsevableCollection<Item> orderedObsevableCollection = MyObservableCollection.Ordering(i => i.OrderKey);

ObsevableCollection will reflect all the changes in MyObservableCollection and OrderKey property of all items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM