C# LINQ- 组合多个 List<T> 并按值排序(.Net 3.5)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/396621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:51:54  来源:igfitidea点击:

LINQ- Combine Multiple List<T> and order by a value (.Net 3.5)

c#.netlinqgenerics

提问by Roberto Bonini

I'm trying to combine a number of List<T> where T:IGetTime(i.e Twill always have method getTime()).

我试图结合一些List<T> where T:IGetTime(即T总是有方法getTime())。

Then I'm trying order the items by the DateTimethat getTime()returns.

然后,我通过尝试订单中的项目DateTimegetTime()回报。

My LINQ looks like this:

我的 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();
    }

I've yet to add an orderby. Which should look somthing like this:

我还没有添加一个orderby. 应该是这样的:

var thestream = from T item in this
                orderby item.getTime() descending
                select item;

Is there anyway to both combine and order the final list????

无论如何都要合并和订购最终列表????

Thanks in advance,

提前致谢,

Roberto

罗伯托

采纳答案by Jon Skeet

You've got three lists here - what exactlyare you trying to order by?

你在这里有三个列表——你到底想按什么顺序订购?

Your cast is incorrect too - the result will be an IEnumerable<X>where Xis an anonymous type with three Ts in.

您的演员表也不正确 - 结果将是一个IEnumerable<X>whereX是一个带有三个Ts的匿名类型。

If the idea is really to concatenatethe three lists and then sort, you want:

如果这个想法真的是连接三个列表然后排序,你想要:

return one.Concat(two)
          .Concat(three)
          .OrderByDescending(x => x.GetTime())
          .ToList();

回答by Amy B

Here's how I'd do it:

这是我的做法:

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

Here's some test code:

下面是一些测试代码:

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

Here's the story:

这是故事:

public static List<T> Combine<T, TKey>
(
  Func<T, TKey> orderingFunction,
  params IEnumerable<T>[] theParams
)
  where TKey : IComparable

This signature declares a method that takes two type parameters, some ordering function and a bunch of collections. Notice that the types T and TKey are not specified explicitly in the test call. The compiler has a little puzzle to figure out what these types are. First it inspects the IEnumerables that it has been given (a and b) and discovers they are IEnumerable of int. Aha, T must be int. Then it inspects the ordering function and sees that it returns the same type that it is passed. Aha, TKey must be int.

这个签名声明了一个方法,它接受两个类型参数,一些排序函数和一堆集合。请注意,在测试调用中未明确指定类型 T 和 TKey。编译器有一个小难题来弄清楚这些类型是什么。首先,它检查给定它的 IEnumerables(a 和 b)并发现它们是 int 的 IEnumerable。啊哈,T 必须是整数。然后它检查排序函数并看到它返回与传递的相同类型。啊哈,TKey 必须是 int。

The whereis kind of funny. OrderBy should check (at compile time) that TKey is IComparable. It only checks at runtime, so we get to do the compile time check in our code.

这里是样的有趣。OrderBy 应该(在编译时)检查 TKey 是否为 IComparable。它只在运行时检查,所以我们可以在我们的代码中进行编译时检查。

paramstakes as many parameters as you like and refers to them be creating an array. Who wants to be limited to three lists?

params接受任意数量的参数,并在创建数组时引用它们。谁想被限制在三个列表中?

        return theParams
            .SelectMany(x => x)
            .OrderBy(orderingFunction)
            .ToList();

SelectManyunpacks a collection of collections. This is a way to flatten one level of hierarchy. OrderBytakes some function that projects each element to an orderable value, and orders the elements according to those values. ToListenumerates the query and returns the list. No surprises there.

SelectMany解压缩集合的集合。这是一种扁平化层次结构的方法。 OrderBy 使用一些函数将每个元素投影到一个可排序的值,并根据这些值对元素进行排序。 ToList枚举查询并返回列表。那里没有惊喜。