Shortest code to calculate list min/max in .NET

后端 未结 4 1979
旧时难觅i
旧时难觅i 2020-12-10 04:45

I\'d like something like

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

Is there a builtin way to

4条回答
  •  失恋的感觉
    2020-12-10 05:18

    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 list = new List();
    // 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); });
    

提交回复
热议问题