how to find minimum difference object of collection in c# linq

Viewed 374

I have collection

Class MyData
{
 int f1;
 int f2;
 int f3;
 int f4;
}

var mycollection =List<MyData>();

I need to return object with minimal difference between field f1 and f3.

I tried below query

mycollection.select(obj => obj.f1 - obj.f3).Min();

But it will return the diff number. I need to return the object. I am kind of struggling to get the object with minimum difference

I also tried this

mycollection.Select(obj => new { MyObject = obj,
                diff = obj.MaxTemparature - obj.MinimumTemparature, obj
            }).Min(obj => obj.diff);
3 Answers

Try this one

 MyData myData = mycollection.OrderBy(o => (o.f1 - o.f3)).First();

You can do below steps to find object by difference F1 - F3.

  1. Calculate difference using .Select() and store it with actual object.
  2. Sort it using .OrderBy() and use difference as a predicate.
  3. Get First record from it.

    var result = myData.Select(x => new {diff = Math.Abs(x.F1 - x.F3), obj = x})  //Step 1
                 .OrderBy(y => y.diff)   //Step 2
                 .FirstOrDefault();     //Step 3
    

Try it online


Or you can perform subtraction without .Select()

    var result = myData.OrderBy(x => Math.Abs(x.F1 - x.F3)).FirstOrDefault();     

Try like below.

 mycollection.OrderBy(x => Math.Abs(x.f1 - x.f3)).FirstOrDefault();

Order your collection by difference and you want minimal difference so used Math.Abs(x.f1 - x.f3). Then take FirstOrDefault object.

Test it here

Related