Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

linq - c# sorting a List<> using Tuple?

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));
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...