Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest code to calculate list min/max in .NET

Tags:

c#

.net

algorithm

I'd like something like

int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);});

Is there a builtin way to do this in .NET?

like image 456
ripper234 Avatar asked Oct 30 '08 15:10

ripper234


1 Answers

Well, if you can't use .NET 3.5, you could always sort the list and then return list[0]. It might not be the fastest way, but it's probably the shortest code, especially if your class already implements IComparable.

List<SomeClass> list = new List<SomeClass>();
// populate the list
// assume that SomeClass implements IComparable
list.Sort();
return list[0];               // min, or
return list[list.Count - 1];  // max

This also assumes, of course, that it doesn't matter which item you return if you have multiple items that are the minimum or maximum.

If your class doesn't implement IComparable, you can pass in an anonymous delegate, something like this:

list.Sort(delegate(SomeClass x, SomeClass y) { return string.Compare(x.Name, y.Name); });
like image 79
Ryan Lundy Avatar answered Sep 17 '22 18:09

Ryan Lundy