c# sorting a List<> using Tuple?

前端 未结 3 800
半阙折子戏
半阙折子戏 2021-01-12 05:24

I need to sort a List<> of MediaItem objects by publish date...the publish date is not a property of the item. So my initial intention was to temporarily tack on a publi

3条回答
  •  没有蜡笔的小新
    2021-01-12 05:57

    You can use the OrderBy( ) LINQ operator to perform the sorting; it allows you to pass a function which extracts the element to sort by. Since the second member of the tuple is the date, we order by Item2.

    var result = list.OrderBy( x => x.Item2 ).ToList();
    

    You can reverse the ordering in LINQ by using OrderByDescending() instead of `OrderBy().

    Also, note that you must either materialize the results or iterate over them, as the OrderBy() method is lazy by default. The example above materializes a copy of the list.

    If you want to sort the list in place (rather than create a new one), you can supply a Comparison delegate to the Sort() method.

     list.Sort( (a,b) => a.Item2.CompareTo(b.Item2) );
    

    However, you can do even better - if you always want to main the list in sorted order, you can use the SortedList class instead ... however you will have to implement a custom IComparer> in that case. In this case, when you add items they will always be maintained in sorted order.

提交回复
热议问题