views:

36

answers:

2

I have a collection of Calendar objects. Calendar has a property Id.

IEnumerable<Calendar> CalendarsToView;

I have another collection of Event Objects. Event objects have a property of CalendarId

IEnumerable<CalendarEvent> Events;

i want to filter the Events collection to only return events where the calendarId is in the CalendarsToView collection.

what is the best way of doing this?

+1  A: 

do a join

var eventsIwant = from e in Events
                  from c in CalendarsToView
                  where c.calendarId =  e.CalendarId
                  select e
Preet Sangha
+1  A: 

This calls for an inner, equijoin:

var eventsInCalendar = from e in Events
                       join c in CalendarsToView on e.CalendarId equals c.Id
                       select e;

var distinctEventsInCalendar = eventsInCalendar.Distinct();

Here's another way of doing it with hash-sets:

var calendarIds = new HashSet<int>(CalendarsToView.Select(c => c.Id));
var distinctEventsInCalendar = Events.Where(e => calendarIds.Contains(e.CalendarId));
Ani