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

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

    var list = new List {14,2,13,11,5,8,21,12,3};
    var tested = 11;
    
    var closestGreater = list.OrderBy(n => n)
                             .FirstOrDefault(n => tested < n); // = 12
    
    var closestLess = list.OrderByDescending(n => n)
                          .FirstOrDefault(n => tested > n); // = 8
    
    if (closestGreater == 0)
        System.Diagnostics.Debug.WriteLine(
            string.Format("No number greater then {0} exists in the list", tested));
    
    if (closestLess == 0)
        System.Diagnostics.Debug.WriteLine(
            string.Format("No number smaler then {0} exists in the list", tested));
    

提交回复
热议问题