Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Get Closest Value?

I have a List, MyStuff has a property of Type Float.

There are objects with property values of 10,20,22,30.

I need to write a query that finds the objects closest to 21, in this case it would find the 20 and 22 object. Then I need to write one that finds the object closes to 21 without going over, and it would return the object with a value of 20.

I have no idea where/how to begin with this one. Help?

Thanks.

Update - wow there are so many awesome responses here. Thanks! I don't know which one to follow so I will try them all. One thing that might make this more (or less) interesting is that the same query will have to apply to LINQ-to-SQL entities, so possibly the answer harvested from the MS Linq forums will work the best? Don't know.

like image 631
Snowy Avatar asked Sep 16 '10 02:09

Snowy


People also ask

How do I find the nearest number in C#?

Or you could just use: var nearest = array. OrderBy(x => Math. Abs((long) x - targetNumber)).

Which of the following LINQ method returns a Boolean value?

The All method of System. LINQ. Queryable class returns a Boolean value if all the elements of the sequence satisfy the provided condition. It returns true if all the elements satisfy the condition otherwise it returns false.

What order are LINQ keywords in to perform a query?

The LINQ query syntax starts with from keyword and ends with select keyword. The following is a sample LINQ query that returns a collection of strings which contains a word "Tutorials". The following figure shows the structure of LINQ query syntax. Query syntax starts with a From clause followed by a Range variable.

What is the return type of a LINQ query in C#?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.


1 Answers

Try sorting them by the absolute value of the difference between the number and 21 and then take the first item:

float closest = MyStuff     .Select (n => new { n, distance = Math.Abs (n - 21) })     .OrderBy (p => p.distance)     .First().n; 

Or shorten it according to @Yuriy Faktorovich's comment:

float closest = MyStuff     .OrderBy(n => Math.Abs(n - 21))     .First(); 
like image 56
amurra Avatar answered Sep 25 '22 13:09

amurra