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<T>
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<Tuple<MediaItem, DateTime>>
in that case. In this case, when you add items they will always be maintained in sorted order.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…