Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 244
Yogesh Avatar asked Dec 22 '22 19:12

Yogesh


2 Answers

Try this one

 MyData myData = mycollection.OrderBy(o => (o.f1 - o.f3)).First();
like image 136
AJITH Avatar answered Mar 25 '23 15:03

AJITH


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();     
like image 25
Prasad Telkikar Avatar answered Mar 25 '23 16:03

Prasad Telkikar