如何在C#中获取二维数组列表的最大值/最小值 [英] How to get max/min of list of 2d array in c#

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

问题描述

我有一个二维数组的列表,像这样:

i have a list of 2d array like this:

    static void Main(string[] args) {
        List<int[,]> kidsL = new List<int[,]>();
        int[,] square1 = new int[8, 8];
        int[,] square2 = new int[8, 8];
        int[,] square3 = new int[8, 8];
        for (int i = 0; i < 8; i++)
            for (int j = 0; j < 8; j++) {
                square1[i, j] = 1;
                square2[i, j] = 2;
                square3[i, j] = 3;
            }
        kidsL.Add(square1);
        kidsL.Add(square2);
        kidsL.Add(square3);
        Console.WriteLine();
        Console.Read();
    }

我想确定每个数组的总和并找到最大/最小一个(在这种情况下,最大为192).

i want to determine sum of every array and find the maxamim/minimum one (in this case the maximum one is 192).

有没有简单的方法可以做到这一点,或者我只是必须循环使用老式的方法?

is there an easy way to do this or am I just going to have to loop through the old fashioned way?

推荐答案

好,您可以使用以下代码从int[,]

Well, you can use the following code to get IEnumarable<int> from int[,]

var enumarable = from int item in square2
                 select item;

此外,您可以使用Cast<int>()方法将int[,]展开为IEnumarable<int>.

Also, you can use a Cast<int>() method in order to unwrap int[,] to IEnumarable<int>.

然后您可以使用Max()Min() linq方法.

Then you can use Max() and Min() linq method.

var min = kidsL.Min(x => (from int item in x select item).Sum());
var max = kidsL.Max(x => (from int item in x select item).Sum());
// or
var min = kidsL.Min(x => x.Cast<int>().Sum())

var Max = (from int[,] array in kidsL
           select (from int item in array select item).Sum())
          .Max();

更新

from int[,] array in kidsL select (from int item in array select item).Sum()查询返回一个包含和的IEnumarable<int>.为了获得最大索引,您应该使用ToListToArray()将IEnumarable强制转换为数组或列表.

from int[,] array in kidsL select (from int item in array select item).Sum() query returns you an IEnumarable<int> which contains sums. In order to have the index of max, you should cast IEnumarable to array or list using ToList or ToArray().

var sumList = (from int[,] array in kidsL
               select(from int item in array select item).Sum())
               .ToList();

var maxSum = sumList.Max();
var maxInd = sumList.IndexOf(maxSum);

sumList是一个整数列表,包含和.因此,您可以使用Max方法获取最大和,并使用IndexOf获取最大值的索引.

sumList is a list of ints and contains sums. So then you can use Max method to get max sum and IndexOf to get index of the max.

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

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