Sorting an observable collection with linq

后端 未结 6 1136
囚心锁ツ
囚心锁ツ 2020-12-16 12:13

I have an observable collection and I sort it using linq. Everything is great, but the problem I have is how do I sort the actual observable collection? Instead I just end

6条回答
  •  余生分开走
    2020-12-16 12:35

    Since the collection doesn't provide any Sort mechanism, this is probably the most practical option. You could implement a sort manually using Move etc, but it will probably be slower than doing in this way.

        var arr = list.OrderBy(x => x.SomeProp).ToArray();
        list.Clear();
        foreach (var item in arr) {
            list.Add(item);
        }
    

    Additionally, you might consider unbinding any UI elements while sorting (via either approach) you only pay to re-bind once:

    Interestingly, if this was BindingList, you could use RaiseListChangedEvents to minimise the number of notifications:

        var arr = list.OrderBy(x => x).ToArray();
        bool oldRaise = list.RaiseListChangedEvents;
        list.RaiseListChangedEvents = false;
        try {
            list.Clear();
            foreach (var item in arr) {
                list.Add(item);
            }
        } finally {
            list.RaiseListChangedEvents = oldRaise;
            if (oldRaise) list.ResetBindings();
        }
    

提交回复
热议问题