2

My solution is

class Test
{
    public int X;
}    

class Program
{
    static void Main(string[] args)
    {
        var arr = new List<Test>();

        var min = arr.Min(x => x.X);
        Test a = arr.First(y => y.X == min);
    }
}

Can this be done in just one-line (only iterating the list once instead of twice)?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
justyy
  • 5,831
  • 4
  • 40
  • 73

3 Answers3

2

why not just order the sequence by the property you want in ascending order and get the first item?

arr.OrderBy(x => x.X).FirstOrDefault();

I just find this and this is a duplicate question

Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
2

There's a popular extension to linq in "MoreLinq" which provides a "MinBy" method:

https://www.nuget.org/packages/MoreLinq.Source.MoreEnumerable.MinBy/

Using that, your code would become:

Test a = arr.MinBy(item => item.X);

Also see https://www.nuget.org/packages?q=id%3Amorelinq

We routinely use the extensions from MoreLinq in many of our projects - it's definitely worth. (Originally written by Jon Skeet and others, I believe.)

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

In the question you want a single iteration, and in response to @dotctor you say that the performance of his solution is worse, thereby saying that performance is important too. Which is more important, performance, or the single iteration?

In this case you can have what you want, but you have to do it without Linq. Loop through the data, and remember the object with the lowest value of X.

var arr = new List<Test>();
Test minimum = null;
foreach (var x in arr) {
    if (minimum == null || x.X < minimum.X) {
        minimum = x;
    }
}
// minimum now contains the object with the lowest value of X.
Maarten
  • 22,527
  • 3
  • 47
  • 68