C# How to find closest number in List<T>

T.Zacks 3,926 Reputation points
2023-01-19T20:13:03.0066667+00:00

suppose few int values stored in List<int> and now i want to find closest number of input value. i got a good solution with linq but without linq how could i achieve this task.

with linq i found this solution.

List<int> list = new List<int> { 4, 2, 10, 7 };
int number = 5;
// find closest to number
int closest = list.OrderBy(item => Math.Abs(number - item)).First();

how to achieve the same output without LINQ?

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,989 questions
No comments
{count} votes

Accepted answer
  1. Dimple Rane 801 Reputation points
    2023-01-19T20:25:26.2633333+00:00

    Without LINQ, you can use a for loop to iterate through the list and keep track of the closest number. You can initialize a variable to store the closest number and the difference between the input number and the current list item, then update it every time a number closer to the input number is found. Here is an example:

    List<int> list = new List<int> { 4, 2, 10, 7 };
    int number = 5;
    int closest = list[0];
    int difference = Math.Abs(number - closest);
    for (int i = 1; i < list.Count; i++)
    {
        int currentDifference = Math.Abs(number - list[i]);
        if (currentDifference < difference)
        {
            closest = list[i];
            difference = currentDifference;
        }
    }
    

    In this example, the variable closest will contain the closest number to the input number.

    No comments

0 additional answers

Sort by: Most helpful