C#排序列表<>使用元组? [英] c# sorting a List<> using Tuple?

查看:134
本文介绍了C#排序列表<>使用元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要排序列表<> MediaItem的对象由发布日期...发布日期不是该项目的属性。所以,我最初的意图是在发布日期属性暂时钉,加载时间了,排序和沟的财产。有人在我的工作,我建议使用元组和LINQ排序......我至今在我的片段测试了这一点,填补了列表与LT;> ...但我不知道如何在该日期之前使用属性排序LINQ。我将继续寻找我的结束,但如果任何人有任何帮助,我将不胜感激。谢谢



 列表与LT元组LT; MediaItem,日期和GT;>名单=新名单,LT元组LT; MediaItem,日期和GT;>(); 

的for(int i = 0; I< = 10;我++)
{
日期时间日期=新的日期时间(2011年,我,1);
MediaItem项目=新MediaItem();
list.Add(新的记录< MediaItem,日期>(项目,日期));
}


解决方案

您可以使用的OrderBy() LINQ运营商进行排序;它可以让你通过它提取元素排序依据的功能。由于元组的第二个成员是日期,我们为了通过项目2

  VAR的结果= list.OrderBy(X => x.Item2).ToList(); 

您可以通过使用扭转LINQ排序 OrderByDescending(),而不是`的OrderBy()。



另外请注意,您必须兑现的结果,或在它们之间迭代,为排序依据()方法是通过默认懒惰。上面的例子物化名单的副本。



如果要排序的地方列表(而不是创建一个新的),你可以提供一个比较< T> 委托给 排序() 方法。

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



不过,你可以做得更好 - 如果你总是希望主要在有序列表中,您可以使用 SortedList的类,而不是...但是你必须实现自定义的IComparer<元组LT; MediaItem,日期和GT;> 在这种情况下。在这种情况下,添加内容时,他们将始终保持有序。


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.

这篇关于C#排序列表&LT;&GT;使用元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆