开发者

c# sorting a List<> using Tuple?

开发者 https://www.devze.com 2023-02-28 09: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 publish date property, load em up,

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 publish date property, load em up, sort, and ditch the property. Someone at my work suggested I use Tuple and sort with LINQ...I've got about this far in my snippet test, filling up the List<>...but I'm not sure how to sort by that date property using LINQ. I'll keep looking on my end but if anyone's got any help I'd appreciate it. Thanks.

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));
            }


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消