Get the number from list using LINQ with specific conditions

linq where condition in list c#
select single value from list using linq
c# linq select from list of objects
linq query to select data from list
c# linq select list within list
linq select query with where clause in c#
c# lambda select where in list
how to write linq query in c#

I have a list of numbers, I would like to get the next >= number than the one I pass, but there's a problem when I pass value that's bigger to the biggest in list. For example when I pass 41 and the biggest in list is 40 it won't work so I'd like it to return 40.

var numbers = new[] {30, 20, 40};

I would like it to work like:

numbers.GetNearest(45) -> 40
numbers.GetNearest(40) -> 40
numbers.GetNearest(31) -> 40
numbers.GetNearest(30) -> 30
numbers.GetNearest(29) -> 30
numbers.GetNearest(1) -> 20

Is this possible with LINQ alone, or is there any well-known algorithm for this?

What I have now is something like:

numbers.OrderBy(n => n).FirstOrDefault(n => n >= minute)

but it doesn't work when I pass value bigger than 40

I don't want the closest number, but the next one >= than the one I pass, but for certain numbers bigger than the biggest in list won't work so I'd like to return just the last one.

Define that special case with DefaultIfEmpty()

var numbers = new[] { 30, 20, 40 };
int result = numbers.Where(n => n >= minute).DefaultIfEmpty(numbers.Last()).First();


Write LINQ queries in C#, The following examples demonstrate some simple LINQ queries by using each how to filter or restrict results by applying conditions with a where clause. List<​int> numbers = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query from num in numbers where num < 3 || num > 7 select num; // Query #2. Notice that your project has a reference to System.Core.dll and a using directive for the System.Linq namespace. Create an in-Memory Data Source. The data source for the queries is a simple list of Student objects. Each Student record has a first name, last name, and an array of integers that represents their test scores in the class. Copy this code into your project.


var numbers = new[]{30, 20, 40};
var number = 25;
var closest = numbers.OrderBy(n => n)
                     .FirstOrDefault(n => n >= number) ?? numbers.Last();

Note : The Cast is just to handle 0 due to default(int) maybe a better way to do this though



Full Demo Here


You could just order by the difference

var closest = numbers.OrderBy(x => Math.Abs((long)x - number))

How to select certain Elements in a list using LINQ-methods?, But it seems that the syntax is a real struggle. Basically I want to add certain objects to a list, where the selected script has a value, in other words  numbers.OrderBy(n => n).FirstOrDefault(n => n >= minute) but it doesn't work when I pass value bigger than 40. I don't want the closest number, but the next one >= than the one I pass, but for certain numbers bigger than the biggest in list won't work so I'd like to return just the last one.

You didn't provide enough details about specific conditions, so I can only give you this answer:

var numbers = new[] {30, 20, 40};

var ordered = numbers.Select(x => (int?)x).OrderBy(x => x);

int? value  = ordered.FirstOrDefault(x => x >= 41) ?? ordered.LastOrDefault();

What is LINQ and Array Processing Using LINQ, Sometimes its necessary to sort an item by a sorting condition, here the code will Print all select n;. Console.WriteLine("Select particular item from list"); WriteLine("Find Second highest number from LIST using LINQ");. The point of LINQ is not really speed, but ease of coding and maintainability. If a query is speed-critical, then you may have to hand-optimize it. – Snowbody Jun 18 '15 at 17:34. Any () works much the same as FirstOrDefault (), but rather than returning the first item, it returns true, and rather than returning null, it returns false. I

Someone posted an answer with Aggregate but not working exactly how I wanted it to work but deleted it. So I came up with my own solution using Aggregate which should be faster than using OrderBy first I think:

numbers.Aggregate((x, y) =>
    var min = Math.Min(x, y);
    return number <= min ? min : Math.Max(x, y);

It took me a while to figure it out but it solves my problem. If you can see any flaws in it, let me know.

Count - Using C# LINQ - A Practical Overview, This form of Count() will return an int indicating the number of elements in the Where(<condition>).Count() . IEnumerable<string> strings = new List<string>  List<T>.FindAll(Predicate<T>) Method is used to get all the elements that match the conditions defined by the specified predicate. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements.

LINQ Count, Count with Predicate. Counts number of items which match specified predicate. IEnumerable<int> items = new List<  How to select some specific column in Lambda Expression LINQ in Entity framework Sep 28, 2014 04:08 PM | akki83 | LINK I want to return only specific column like Month, ReportType,Year and also one column as NewColumn=Month+"-"+Year+"-"+ReportType and want to bind this NewColumn in gridview. i am using below method by filtering criteria.

C# filter list tutorial - filtering a list in C#, We use iteration, LINQ, and built-in FindAll() method. The example finds out all integer values that are greater than zero. The FindAll() method retrieves all the elements that match the conditions defined by the specified predicate. { get; set​; } } class Program { static void Main(string[] args) { List<Car>  Its functionalities are located in the System.Data.Linq assembly. using System.Data.Linq; A Simple LINQ query requires the following 3 things: Entity Class. Data Context . LINQ query. Coding LINQ to SQL Query . In this we will use LINQ to SQL to retrieve all employee details from the EMP Table, as described in the following:

[Solved] How do I return a single value from a list using LINQ , In particular, I would like a solution that uses the special LINQ keywords ('select', '​where', etc.) and also the standard C# LINQ functions ( Select(),  using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Find { class Program { private static string IDtoFind = "bk109"; private static List<Book> Books = new List<Book>(); public static void Main(string[] args) { FillList(); // Find a book by its ID.

  • Your title talks about "specific conditions" but you don't describe what those are. We can maybe guess from the code that you've written, but as you've said that doesn't work, it's hard to say for sure. Please provide more details about what you're trying to achieve.
  • Possible duplicate of How to get the closest number from a List<int> with LINQ?
  • Do you want the nearest bigger number and in case it does not exist then the nearest smaller number? That is the only way your cae of 31->40 and 45 -> 40 can be explained?
  • @peeyushsingh yeah
  • @apocalypse fair point, I can just check if it's empty first and return 0, but it depends on the case.
  • This is not pure Linq.
  • @apocalypse since the input is a array, I'd prefer Array.Sort(numbers); over numbers = numbers.OrderBy(x => x).ToArray(); because it's faster
  • @fubo: Yeah I know. But what if we have array of 1,000,000 numbers? What if we don't want to modify input array? Or we don't have array but IEnumerable?
  • The answer is DefaultIfEmpty. The fact that there is an Array.Sort is irrevelant.
  • what if I want it to return 30 when I pass 21,22,23 or 24?
  • @Konrad why would you want that? That's not the nearest number. Update your question and explain what you actually want
  • I think it's unfair to downvote this given that is answered the original question.
  • Having said that, the Cast in the update is absolutely horrible.
  • Recommending awful code means you should have that pizza taken off you. You should know better...