我有一个List<List<double>>
我需要找到一个列表 MyList,例如,其中 MyList[0] 是列表中所有第一个元素的最大值。
示例,只是为了清楚起见:
第一个列表包含 (3,5,1),第二个包含 (5,1,8),第三个包含 (3,3,3),第四个包含 (2,0,4)。
我需要找到一个包含 (5, 5, 8) 的列表。
我不需要列表 (5,8,3,4)。
当然我知道如何使用嵌套 for 循环来做到这一点。 我想知道是否有 linq 方式,相信我,我不知道从哪里开始。
最佳答案
var source = new List<List<int>> {
new List<int> { 3, 5, 1 },
new List<int> { 5, 1, 8 },
new List<int> { 3, 3, 3 },
new List<int> { 2, 0, 4 }
};
var maxes = source.SelectMany(x => x.Select((v, i) => new { v, i }))
.GroupBy(x => x.i, x => x.v)
.OrderBy(g => g.Key)
.Select(g => g.Max())
.ToList();
返回 { 5, 5, 8}
,这就是您所需要的。当源列表也有不同数量的元素时也将起作用。
奖金
如果您也需要 Min
版本,并且想要防止代码重复,您可以使用一点功能:
private static IEnumerable<TSource> GetByIndex<TSource>(IEnumerable<IEnumerable<TSource>> source, Func<IEnumerable<TSource>, TSource> selector)
{
return source.SelectMany(x => x.Select((v, i) => new { v, i }))
.GroupBy(x => x.i, x => x.v)
.OrderBy(g => g.Key)
.Select(g => selector(g));
}
public static IEnumerable<TSource> GetMaxByIndex<TSource>(IEnumerable<IEnumerable<TSource>> source)
{
return GetByIndex(source, Enumerable.Max);
}
public static IEnumerable<TSource> GetMinByIndex<TSource>(IEnumerable<IEnumerable<TSource>> source)
{
return GetByIndex(source, Enumerable.Min);
}
关于c# - 获取列表列表中的最大值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735016/