在列表列表中获取最大值列表 [英] get a List of Max values across a list of lists

查看:31
本文介绍了在列表列表中获取最大值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List< List< double>> ,并且我需要找到一个列表MyList,其中MyList [0]例如是List的所有第一元素的最大值.例子,只是为了清楚:第一个列表包含(3,5,1),第二个列表包含(5,1,8),第三个列表包含(3,3,3),fourt包含(2,0,4).我需要找到一个带有(5,5,8)的列表.我不需要列表(5,8,3,4).

I have a List<List<double>> and I need to find a List MyList where MyList[0], for instance, is the Max of all the first elements of the List. Example, just to be clear: First list contains (3,5,1), second contains (5,1,8), third contains (3,3,3), fourt contains (2,0,4). I need to find a list with (5, 5, 8). I do NOT need the list (5,8,3,4).

我当然知道如何嵌套使用循环.我想知道是否有linq方式,并相信我我不知道从哪里开始.

Of course i know how to do it with nested for cycles. I'd like to know if there's a linq way and believe me i don't know where to start from.

推荐答案

尝试以下方法:

 // Here I declare your initial list.
 List<List<double>> list = new List<List<double>>()
 {
     new List<double>(){3,5,1},
     new List<double>(){5,1,8},
     new List<double>(){3,3,3},
     new List<double>(){2,0,4},
 };

 // That would be the list, which will hold the maxs.
 List<double> result = new List<double>();


 // Find the maximum for the i-st element of all the lists in the list and add it 
 // to the result.
 for (int i = 0; i < list[0].Count-1; i++)
 {
     result.Add(list.Select(x => x[i]).Max());
 }

注意:仅当列表中包含的所有列表具有相同数量的元素时,此解决方案才有效.

Note: this solution works only, when all the lists that are contained in the list have the same number of elements.

这篇关于在列表列表中获取最大值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆