有没有一种简单的方法可以获取几个相同大小的列表,并使用 linq 在每个索引中创建一个新的最小/最大值?我的意思是如何比较相同索引的项目并选择哪个是最大或最小,如下所示:
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}
我简化了这些循环以使其看起来更清晰。我知道我可以使用 Concat 和 GroupBy,然后从每个中选择 Max,但是对于没有键值的简单类型和类,我无法弄清楚。
编辑:我应该更准确。示例中的列表是手动分配的,但我在询问解决方案,该解决方案对于比较的任何数量的列表都是灵活的。此外,列表的大小始终相同。
最佳答案
List Of Lists 的大小没有限制,列表可以是任意长度。
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();
关于c# - 使用linq将几个列表合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18341902/