devuxer
devuxer

Reputation: 42394

Obtaining the min and max of a two-dimensional array using LINQ

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?

Upvotes: 11

Views: 41512

Answers (4)

Jake Kalstad
Jake Kalstad

Reputation: 2065

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.

Upvotes: 0

dondublon
dondublon

Reputation: 701

here is variant:

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

where aarray is int[,]

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839234

This seems to work:

IEnumerable<int> allValues = myArray.Cast<int>();
int min = allValues.Min();
int max = allValues.Max();

Upvotes: 8

Lee
Lee

Reputation: 144216

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

Upvotes: 33

Related Questions