简体   繁体   English

使用linq将几个列表合并为一个

[英]Merging few lists into one using linq

Is there a simple way to take few lists of the same size and create a new one ouf of their min/max values in each index with linq? 是否有一种简单的方法可以使用相同大小的几个列表并使用linq在每个索引中创建一个新的最小值/最大值? I mean how to compare items at same index and pick which one is Max or Min like here: 我的意思是如何比较相同索引的项目,并选择哪一个是Max或Min,如下所示:

List<List<int>> Some2dList = new List<List<int>>
                 { new List<int> { 1, 2, 3, 4, 5 }, 
                   new List<int> { 5, 4, 3, 2, 1 } } ;
List<int> NewList = new List<int>(5);

for(int i=0; i< 5; i++)
{
    int CurrentHighest=0;
    for(int j=0; j<2; j++)
    {
        if (Some2dList[j][i] > CurrentHighest)
            CurrentHighest = Some2dList[j][i];
    }
    NewList.Add(CurrentHighest);
}
//Which gives me {5,4,3,4,5}

I've simplified those loops to look clearlier. 我简化了那些循环看起来更清晰。 I know I could use Concat and GroupBy, and then select Max out of each, but for simple types and classes without a key value I can't figure it out. 我知道我可以使用Concat和GroupBy,然后从每个中选择Max,但对于没有键值的简单类型和类,我无法弄明白。

edit: I shoul've been more precise. 编辑:我应该更精确。 List in example are assigned manually, but I'm asking about solution, that would be flexible for ANY amount of lists compared. 示例中的列表是手动分配的,但我问的是解决方案,这对于任何数量的列表都是灵活的。 Also, lists are always same sized. 此外,列表总是大小相同。

No limit on the size of List Of Lists and lists can be any length. 列表和列表的大小没有限制可以是任何长度。

List<List<int>> Some2dList = new List<List<int>>{ 
        new List<int> { 1, 2, 3, 4, 5 }, 
        new List<int> { 5, 4, 3, 2, 1 },
        new List<int> { 8, 9 } 
        };
var res = Some2dList.Select(list => list.Select((i, inx) => new { i, inx }))
            .SelectMany(x => x)
            .GroupBy(x => x.inx)
            .Select(g => g.Max(y=>y.i))
            .ToList();

This should do what you are looking for: 这应该做你想要的:

List<int> newList = Some2dList[0].Select((x, column) => Math.Max(x, Some2dList[1][column])).ToList();

The trick is taking the overload of Select that allows you to have the index of the item you are working with in the lambra expression : this makes possible compare two items in the two different lists placedat the same index. 诀窍是使用Select的重载,允许您在lambra表达式中获得正在使用的项目的索引:这使得可以比较放置在同一索引中的两个不同列表中的两个项目。 Obviously if it's the min you are looking for, use Math.Min instead of Math.Max. 显然,如果它是您正在寻找的最小值,请使用Math.Min而不是Math.Max。

Just one thing, I take for granted that the two sublists have the same number of elements. 只有一件事,我理所当然地认为这两个子列表具有相同数量的元素。

Little bit abnormal but seems to work. 有点不正常,但似乎工作。 It assumes there is one list though 它假设有一个列表

Enumerable.Range(0, Some2dList.FirstOrDefault().Count)
   .Select(columnIndex => 
       Some2dList.Max(row => row[columnIndex]))
   .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM