c#如何从列表的列表中获取最大值
本文关键字:列表 获取 最大值 | 更新日期: 2023-09-27 18:10:51
我有一个列表列表,我从一个"制表符"分隔的字符串创建。我不使用2d数组,而是使用列表的列表,因为我不知道创建数组的大小。
就像
0 0
16.0000 0
15.0000 15.0000
0 15.0000
2.7217 5.6904
3.7217 5.6904
我现在想从每一列中找出最大值和最小值。所以如果你用上面的例子,
最大值为:16.0000 15.0000最小值是0 0
for (int i = 0; i < size[0]; i++)
{
// Create size[0] x size[1] array
obstVertex.Add(new List<double>());
for (int y = 0; y < size[1]; y++)
{
obstVertex[i].Add(Convert.ToDouble(split[i+(y*size[0])]));
}
}
如何使用linq找到最大值或最小值??
Thanks in advance
List<List<double>> myList;
myList.Add(new List(new double[] { 0, 16, 15, 0, 2.7217, 3.7217 }));
myList.Add(new List(new double[] { 0, 0, 15, 15, 5.6904, 5.6904 }));
List<double> maxList = myList.Select(l => l.Max()).ToList();
List<double> minList = myList.Select(l => l.Min()).ToList();
尝试如下:
class Program
{
static void Main(string[] args)
{
var l = new List<List<double>>() {new List<Double>() {0, 16.0000, 15.0000, 0, 2.7217, 3.7217},
new List<Double>() {0, 0, 15.0000, 15.0000, 5.6904, 5.6904}};
int i = 1;
var result = from sublist in l
select new { min = sublist.Min(), max = sublist.Max(), index = i++ };
foreach (var r in result)
Console.WriteLine(String.Format("Index: {0} Min: {1} Max: {2}",r.index, r.min, r.max));
Console.ReadKey();
}
}
它将获取列表的列表中每个子列表的最小值和最大值。
我假设是这样声明的:
List<List<double>> obstVertex;
那么你可以这样做
var minima = Enumerable.Range(0, obstVertex[0].Count - 1)
.Select (colIndex => obstVertex.Select(row => row[colIndex]).Min())
static void Main(string[] args)
{
List<List<double>> lists = new List<List<double>>() {
new List<double>(){0 , 0 } ,
new List<double>(){16.0000 , 0 } ,
new List<double>(){16.0000 , 15.0000 } ,
new List<double>(){0 , 15.0000 } ,
new List<double>(){2.7217 , 5.6904 } ,
new List<double>(){3.7217 , 5.6904 }
};
var r = new {
col1_max = (from x in lists select x[0]).Max(),
col1_min = (from x in lists select x[0]).Min(),
col2_max = (from x in lists select x[1]).Max(),
col2_min = (from x in lists select x[1]).Min(),
};
Console.WriteLine(string.Format("col1_max = {0}'r'ncol1_min = {1}'r'ncol2_max = {2}'r'ncol3_max = {3}", r.col1_max , r.col1_min , r.col2_max , r.col2_min));
Console.Read();
}