1

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

0

4 Answers 4

7

How about this?

Ordered array:

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

Unordered array:

numbers.Where(x => x < 135).Max();
Sign up to request clarification or add additional context in comments.

Comments

3

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

e.g.

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

2 Comments

First(n => n < 135) in your example will return 121 while OP is expecting 131
Good Catch, I am modifying the answer now.
2

Find the number itself, since you know the number you want, you do not need any range.

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

Comments

0

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);

}

}

1 Comment

Why this is the accepted answer? This is exactly the solution I proposed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.