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

后端 未结 8 625
猫巷女王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:38

    You can do this using a binary search. If your searching for 11, well obviously you'll get the index your after. If you search for 10 and use the bitwise complement of the result, you'll get the closest match.

       List list = new List(){3,5,8,11,12,13,14,21};
    
       list.Sort();
    
       int index = list.BinarySearch(10);
    
       int found =  (~index)-1;
    
       Console.WriteLine (list[found]); // Outputs 8
    

    The same goes searching in the other direction

    int index = list.BinarySearch(15);
    
    Console.WriteLine("Closest match : " + list[+~index]); // Outputs 21
    

    Binary searches are also extremely fast.

提交回复
热议问题