LINQ to find the closest number that is greater / less than an input

后端 未结 8 622
猫巷女王i
猫巷女王i 2021-02-05 19:57

Suppose I have this number list:

List = new List(){3,5,8,11,12,13,14,21}

Suppose that I want to get the closest number th

8条回答
  •  走了就别回头了
    2021-02-05 20:55

    Here is my way hope this helps somebody!

    List list = new List { 4.0f, 5.0f, 6.0f, 10.0f, 4.5f,  4.0f, 5.0f, 6.0f, 10.0f, 4.5f, 4.0f, 5.0f, 6.0f, 10.0f };
    float num = 4.7f;
    
    float closestAbove = list.Aggregate((x , y) => (x < num ? y : y < num ? x : (Math.Abs(x - num)) < Math.Abs(y - num) ? x : y));
    float closestBelow = list.Aggregate((x , y) => (x > num ? y : y > num ? x : (Math.Abs(x - num)) < Math.Abs(y - num) ? x : y));
    
    Console.WriteLine(closestAbove);
    Console.WriteLine(closestBelow);
    
    

    This means you dont have to order the list

    Credit: addapted from here: How to get the closest number from a List with LINQ?

    The Expanded Code

    float closestAboveExplained = list.Aggregate((closestAbove , next) => {
        if(next < num){
            return closestAbove;
        }
    
        if(closestAbove < num){
            return next;
        }
    
        else{
            if(Math.Abs(closestAbove - num) < Math.Abs(next - num)){
                return closestAbove;
            }
        }
        return next;
    });
    
    

提交回复
热议问题