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);
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
.
.Select()
and store it with actual object..OrderBy()
and use difference as a predicate.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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With