0
IEnumerable<T>.Min(Func<T, TResult>)

performs transformation first and then selects minimum value. Is there any standard linq operation I can perform to return original element? I get that I can use Min() and then Where() to achieve this, but this has running time of O(2n) instead of optimal O(n). To illustrate what I mean:

var fooList = new List<Foo>
{ 
    new Foo { Bar1 = 10, Bar2 = 0 },
    new Foo { Bar1 = 8, Bar2 = 1 },
    new Foo { Bar1 = 6, Bar2 = 7 }
};

var foo = fooList.Min(f => f.Bar2); // magic happens here
// foo is of type Foo with Bar1 = 10 Bar2 = 0
markovcd
  • 147
  • 1
  • 7
  • 3
    Possible duplicate of [How to use LINQ to select object with minimum or maximum property value](http://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value) – BJ Myers Oct 02 '15 at 15:38

1 Answers1

3

There is no standard operator but you can utilize Aggregate:

 var foo = fooList.Aggregate((f1, f2)=> f1.Bar2 < f2.Bar2 ? f1 : f2);
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92