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

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

    This is my answer

    List myList = new List() { 3, 5, 8, 11, 12, 13, 14, 21 };
        int n = 11;
        int? smallerNumberCloseToInput = (from n1 in myList
                                        where n1 < n
                                        orderby n1 descending
                                        select n1).First();
    
        int? largerNumberCloseToInput = (from n1 in myList
                                        where n1 > n
                                        orderby n1 ascending
                                        select n1).First();
    

提交回复
热议问题