简体   繁体   中英

How to find specific number from array?

I have some code here for finding only left first small number from an array.

public void Test() {
    int[] numbers = { 121, 124, 131, 135, 219, 287, 361, 367, 382, 420 };
    var onlyfirstNumbersLessThanGiven = numbers.TakeWhile(n => n < 135);
    Console.WriteLine("First numbers less than ");
    foreach (var n in onlyfirstNumbersLessThanGiven)
    {
        Console.WriteLine(n);
    } 
}

How to find only 131 from above array? Please help me

How about this?

Ordered array:

numbers.LastOrDefault(x => x < 135);

Unordered array:

numbers.Where(x => x < 135).Max();

Although Renan's answer is perfectly correct, why not just use First(), edited or TakeWhile() with Last()?

eg

int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 
                    83, 23, 87, 435, 67, 12, 19 };

int first = numbers.First(number => number > 80);
int firstSmaller = numbers.TakeWhile(number => number < 80).Last(); // returns 65 since its the first one smaller than 80 in the series

Console.WriteLine(first);

And to match it with your situation:

public void Test() {
    int[] numbers = { 121, 124, 131, 135, 219, 287, 361, 367, 382, 420 };
    var onlyfirstNumbersLessThanGiven = numbers.TakeWhile(n => n < 135).Last();
    Console.WriteLine("First numbers less than ");
    Console.WriteLine(onlyfirstNumbersLessThanGiven);
}

There are restrictions: the array is assumed to be sorted, and must be in ascending order.

Thanks to Ivan Stoev for pointing out my mistake

查找数字本身,因为您知道所需的数字,所以不需要任何范围。

numbers.Where(x => x == 131);

This example helps to clear.

public void Test()

{

int[] numbers = { 121, 324, 431, 135, 119, 287, 361, 367, 382, 420 };

var OFNLTG = numbers.Where(x => x < 121).Max();
Console.WriteLine("First Max Number:");

{ Console.WriteLine(OFNLTG);

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM