I have a list of items.
I have to select item with minimum difference between two of its properties.
Eg : Student { string Name, int ScoredMarks, int TotalMarks }
Note : Total marks will not be the same for all students.
I have to select the student with least difference of TotalMarks and ScoredMarks.
I was able to do this way
int minDiff = students.Min(x => (x.TotalMarks - x.ScoredMarks));
var result = from s in students
where s.TotalMarks - s.ScoredMarks == minDiff
select s;
Can i achieve it in a single statement? What would be the perfomance of doing this way?
which would be optimistic
You can use
Math.Absto get the absolute difference, order by it and take the first.If you want the best performance you should use
MinByof Skeets MoreLinq. My approach needs to order all items by the value before it takes the one with the lowest difference.Then you could use
GroupBy: