Sorting an observable collection with linq

后端 未结 6 1124
囚心锁ツ
囚心锁ツ 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:21

    Note that in Linq, you are given an IEnumerable from your query, and that query has not executed yet. Therefore, the following code only runs the query once, to add it to an ObservableCollection:

    var query = from x in Data
                where x.Tag == "Something"
                select x;
    
    foreach(var item in query)
        MyObservableCollection.Add(item);
    

    Take a look at the "OrderBy" extension on IEnumerable:

    foreach(var item in query.OrderBy(x => x.Name))
        MyObservableCollection.Add(item);
    

提交回复
热议问题