Vahid
Vahid

Reputation: 5454

Get the next number in a list of numbers using LINQ

I have a list of numbers as below:

var mylist = new List<double> {1, 5, 8, 10, 12};

How can I get the number after a specific number. I want an LINQ expression that receives for example 8 and gives me 10;

Upvotes: 3

Views: 611

Answers (3)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101711

This should also work if you do not have duplicate numbers.

int index = mylist.IndexOf(8);

if (index != -1)
{
   double result = index == mylist.Count - 1 ? mylist[index] : mylist[index + 1];
}

Upvotes: 2

invernomuto
invernomuto

Reputation: 10221

This should work,

var mylist = new List<double> { 1, 5, 8, 10, 12 };
double p = 8;

var result = mylist.Where(x => x > p).Take(1).SingleOrDefault();

Upvotes: 1

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

You can use the following:

double result = mylist.SkipWhile(n => n != 8).Skip(1).First();

Upvotes: 7

Related Questions