C# LINQ-组合多个列表<;T>;并按值(.Net 3.5)排序
我正在尝试组合一些C# LINQ-组合多个列表<;T>;并按值(.Net 3.5)排序,c#,.net,linq,generics,C#,.net,Linq,Generics,我正在尝试组合一些列表,其中T:IGetTime(即T将始终具有方法getTime()) 然后,我尝试按照getTime()返回的DateTime对项目进行排序 我的LINQ看起来像这样: public static List<T> Combine(List<T> one, List<T> two, List<T> three) { var result = from IGetTime item in one
列表,其中T:IGetTime
(即T
将始终具有方法getTime()
)
然后,我尝试按照getTime()
返回的DateTime
对项目进行排序
我的LINQ看起来像这样:
public static List<T> Combine(List<T> one, List<T> two, List<T> three)
{
var result = from IGetTime item in one
from IGetTime item2 in two
from IGetTime item3 in three
select new{ item, item2, item3 };
return result.ToList();
}
var thestream = from T item in this
orderby item.getTime() descending
select item;
是否有合并和订购最终列表的方法
提前感谢,
罗伯托你这里有三张清单——你到底想点什么 您的强制转换也不正确-结果将是一个
IEnumerable
,其中X
是一个匿名类型,包含三个T
s
如果要将三个列表连接起来,然后进行排序,则需要:
return one.Concat(two)
.Concat(three)
.OrderByDescending(x => x.GetTime())
.ToList();
我是这样做的:
public static List<T> Combine<T, TKey>
(
Func<T, TKey> orderingFunction,
params IEnumerable<T>[] theParams
)
where TKey : IComparable
{
return theParams
.SelectMany(x => x)
.OrderBy(orderingFunction)
.ToList();
}
打开集合的集合。这是一种扁平化一级层次结构的方法。
获取将每个元素投影为可排序值的函数,并根据这些值对元素排序。
枚举查询并返回列表。这并不奇怪。C#知道x将有一个GetTime方法(或将其转换为IGetTime)仅仅是因为where T:IGetTime吗?如果不是,Lambda需要调整为x=>((IGetTime)x)。GetTime()C~不知道。T在clas decleration:public class TimeStream:List中被明确定义为T:IGetTime哇,它在没有演员的情况下确实可以工作,这不禁让人觉得这让C#magix pixie dust走得太远了。@Roberto:仍然有魔法在发生,它在默默地向IGetTime施放x,即使T的类型是其他类型。它是通过检查限制列表中的每个接口来寻找匹配的GetTime()签名来实现的。@AnthonyWJones:泛型的许多好处是用编译时类型检查来代替运行时强制转换。类型都在那里,由程序员指定。编译器不必太费劲地检查这些实例是否具有该方法。
public static void Test1()
{
List<int> a = new List<int>() { 1, 2, 3 };
List<int> b = new List<int>() { 3, 2, 1 };
List<int> c = CombineLists.Combine(i => i, a, b);
c.ForEach(i => Console.WriteLine(i));
}
public static List<T> Combine<T, TKey>
(
Func<T, TKey> orderingFunction,
params IEnumerable<T>[] theParams
)
where TKey : IComparable
return theParams
.SelectMany(x => x)
.OrderBy(orderingFunction)
.ToList();