Mehrdad Kamali
Mehrdad Kamali

Reputation: 87

How to get max/min of list of 2d array in 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();
    }

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?

Upvotes: 2

Views: 5240

Answers (2)

Ivan Gritsenko
Ivan Gritsenko

Reputation: 4236

Cast<int> method will flatten array to IEnumerable<int> which allows using LINQ.

var max = kidsL.Max(square => square.Cast<int>().Sum());
var min = kidsL.Min(square => square.Cast<int>().Sum());

You should also be aware of possible overflow which can happen if values and dimensions of the array would be large.

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

Although the solution is concise it has the same efficiency as looping over every element of every array. But that's indeed is an easy way.

Upvotes: 2

Valentin
Valentin

Reputation: 5488

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

var enumarable = from int item in square2
                 select item;

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

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())

or

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

Update

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 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.

Upvotes: 3

Related Questions