Bronzato
Bronzato

Reputation: 9362

Using LINQ expression to get previous element from a collection

I need to write a LINQ expression based on the following scenario:

public class Meeting
{
   public int Id { get; set; }
   public DateTime Date { get; set; }
   public bool Selected { get; set; }    
}

List<Meeting> Meetings

Using LINQ expression, how to retrieve the metting occurring just before the first one which is selected ?

For example in the liste below I need to retrieve the meeting Id 2.

Upvotes: 1

Views: 415

Answers (2)

sloth
sloth

Reputation: 101162

You could use TakeWhile and LastOrDefault.

Meetings.TakeWhile(m => !m.Selected).LastOrDefault()

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503859

You could use TakeWhile and LastOrDefault:

var meeting = Meetings.TakeWhile(m => !m.Selected)
                      .LastOrDefault();

if (meeting != null) 
{
    // Use the meeting
}
else
{
    // The first meeting was selected, or there are no meetings
}

TakeWhile basically stops when it hits the first item that doesn't match the predicate - it's like a Where that stops early, in other words.

You need to be careful with ordering though - you're pretty much assuming there's a bunch of unselected meetings, followed by selected ones.

Upvotes: 6

Related Questions