Mike Cole
Mike Cole

Reputation: 14713

Using Linq to find the element after a specified element in a collection

I have an ordered list of People. I have a person that I know exists in that collection. How can I determine which person is next in the list?

Upvotes: 20

Views: 10026

Answers (3)

TarmoPikaro
TarmoPikaro

Reputation: 5243

You can use code like this:

String toDir = Environment.GetCommandLineArgs().SkipWhile(x => x != "/to").Skip(1).Take(1).FirstOrDefault();

This value gets == null if "/to" command line argument not given, non-null if path was provided.

Upvotes: 0

Ani
Ani

Reputation: 113402

You could do something like this:

IEnumerable<Person> persons = ..

var firstPersonAfterJack = persons.SkipWhile(p => p.Name != "Jack")
                                  .ElementAt(1); //Zero-indexed, means second

The idea is to produce a sequence resulting in skipping elements until you meet the condition, then take the second element of that sequence.

If there's no guarantee that the query will return a result (e.g. a match is never found, or is the last element of the sequence), you could replace ElementAt with ElementAtOrDefault, and then do a null-test to check for success / failure.

I notice you say in your question that you have an ordered list of people. If you could explain what that means in more detail, we might be able to provide a better answer (for example, we may not have to linear-search the sequence).

Upvotes: 38

Trystan Spangler
Trystan Spangler

Reputation: 1769

SkipWhile is a method that takes a predicate and skips everything until the predicate is false. It returns that element and everything after.

var remainingPeople = collectionOfPeople.SkipWhile(p => !isThePerson(p));
if (remainingPeople.Count() == 1)
{
    // the person was the last in the list.
}
var nextPerson = remainingPeople.Skip(1).First();

where isThePerson is a method that takes a person and returns true if it is the person you are interested it.

Upvotes: 5

Related Questions