11

How would you obtain the min and max of a two-dimensional array using LINQ? And to be clear, I mean the min/max of the all items in the array (not the min/max of a particular dimension).

Or am I just going to have to loop through the old fashioned way?

devuxer
  • 41,681
  • 47
  • 180
  • 292

4 Answers4

32

Since Array implements IEnumerable you can just do this:

var arr = new int[2, 2] {{1,2}, {3, 4}};
int max = arr.Cast<int>().Max();    //or Min
Lee
  • 142,018
  • 20
  • 234
  • 287
  • 5
    For future searchers, http://stackoverflow.com/a/641565 for Jagged Arrays ie. `int[][] SomeArray = ...;`, use `var Flattened = SomeArray.SelectMany(x => x)` which aggregates the enumerators. Then you can just do `Flattened.Max()` for example. – HodlDwon Aug 19 '13 at 19:59
  • 2
    Josh: Correct me if I'm wrong, but the way this looks to me, you would copy the entire array into another flattened array just to do a maximum search, which incurs firstly the copying overhead, and then another O(n) and hence has terrible overall complexity for such a simple problem. Sometimes elegance and brevity really isn't everything. – Tom Aug 02 '14 at 12:15
8

This seems to work:

IEnumerable<int> allValues = myArray.Cast<int>();
int min = allValues.Min();
int max = allValues.Max();
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

here is variant:

var maxarr = (from int v in aarray select v).Max();

where aarray is int[,]

dondublon
  • 701
  • 1
  • 6
  • 13
0

You could implement a List<List<type>> and find the min and max in a foreach loop, and store it to a List. Then you can easily find the Min() and Max() from that list of all the values in a single-dimensional list.

That is the first thing that comes to mind, I am curious of this myself and am gonna see if google can grab a more clean cut approach.

CarenRose
  • 1,266
  • 1
  • 12
  • 24
Jake Kalstad
  • 2,045
  • 14
  • 20
  • How would you even get a two-dimensional array into a list in the first place? – devuxer Jun 15 '10 at 21:41
  • Ah, I thought to far ahead, now I realize if you were to get the array into a list, you could use the code to get the MIN/MAX out of the same loop i envisioned to populate the Lists. :/ tis been a long mourning with not enough coffee :D – Jake Kalstad Jun 15 '10 at 21:49
  • You can flatten the array, @devuxer – Zimano Dec 29 '17 at 17:47