2

I'm using Math.Max and Math.Min to find the largest and smallest decimals in the following code:

decimal[] numbers = { d1, d2, d3, d4, d5, d6, d7, d8, d9, d10 };
decimal biggestNumber = numbers.Max();
decimal lowestNumber = numbers.Min();
lblS1Val.Text = biggestNumber.ToString();
lblO1Val.Text = lowestNumber.ToString();

I'd like to actually find the three largest and three smallest numbers. Can I do that with Math.Max/Min?

66Mhz
  • 225
  • 2
  • 4
  • 12
  • Max/Min just return one value... to find three values you needs to use other solutions like linq. – lem2802 Apr 30 '15 at 19:55

2 Answers2

6

While you could use Math.Min and Math.Max for what you want, there is a far easier way using LINQ To Objects, as they are designed to work on collections, which is what we're dealing with here:

var smallestThree = numbers.OrderBy(x => x).Take(3);
var largestThree = numbers.OrderByDescending(x => x).Take(3);

Note this will return IEnumerable<decimel>, so if you want to ToString it, you can use string.Join:

lblS1Val.Text = string.Join(", ", largestThree);
lblO1Val.Text = string.Join(", ", smallestThree);
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Wow, that is pretty simple! Thanks for your quick reply. – 66Mhz Apr 30 '15 at 20:11
  • Is there a way to return the variable names from which the three largest and three smallest numbers are stored? For instance, in addition to returning the values of the largest and smallest, can I also return the variable names where the three largest and smallest are being stored? – 66Mhz Apr 30 '15 at 20:17
  • 1
    @66Mhz It is *possible* to do what you're asking, but will require a way more complex operation. You can read [this](http://stackoverflow.com/questions/72121/finding-the-variable-name-passed-to-a-function-in-c-sharp) if you *really* need that. Although, if you had a class containing a `Name` property and a `Value` property, you could easily do that. – Yuval Itzchakov Apr 30 '15 at 20:24
  • Thanks for the link, looks like I have some research to do. – 66Mhz Apr 30 '15 at 20:42
5
numbers.OrderBy(n=>n).Take(3);
numbers.OrderByDescending(n=>n).Take(3);
Habib
  • 219,104
  • 29
  • 407
  • 436
Dom
  • 716
  • 4
  • 11
  • Because they aren't needed. OrderBy will sort largest to smallest, and Take(3) will return the first 3 results. OrderByDescending does the opposite. – Psymunn Apr 30 '15 at 23:17