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.
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.
See more on this question at Stackoverflow