c# - 获取列表列表中的最大值列表

标签 c# linq list max

我有一个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/

相关文章:

c# - 读取xml文件并将id的值写入C#中的相关文本框中

c# - 获取所有进程及其相应的应用程序域

c# - 无法从 xtragridview 获取点击行的数据

c# - 列表属性 setter

来自 psycopg2 PostgreSQL 查询的 Python 数组操作

c# - 使用循环或其他方式简化 C# 行

C# LINQ 检测插入

c# - 在 C# 中读取 csv 文件以提高时间效率的最佳方法

asp.net-mvc - 如何使用 Linq to SQL 配置 mvc mini profiler?

c# - 在列表中查找 int 的索引