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.

  • Id:1 Date:11/1 Selected: false
  • Id:2 Date:12/1 Selected: false
  • Id:3 Date:13/1 Selected: true
  • Id:4 Date:14/1 Selected: true
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow