c# sorting a List<> using Tuple?

[亡魂溺海] 提交于 2019-12-01 04:22:46

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.

One way would be to use the List<T>.Sort method, using a lambda-expression to create the appropriate Comparison<T> delegate.

// Sorts tuples in chronological order. To use reverse chronological order,
// use t2.Item2.CompareTo(t1.Item2) instead.
list.Sort((t1, t2) => t1.Item2.CompareTo(t2.Item2));

This of course assumes that there are no null-references in the list, which there can't be in your example.

List<Tuple<MediaItem, DateTime>> list = new List<Tuple<MediaItem, DateTime>>();

 for (int i = 0; i <= 10; i++)
 {
      DateTime date = new DateTime(2011, i, 1);
      MediaItem item = new MediaItem();
      list.Add(new Tuple<MediaItem, DateTime>(item, date));
 }

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

foreach (var element in list)
{
    Console.WriteLine(element);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!