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?
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With