LINQ "Except" statement

I have a list of event IDs that I want to exclude from my select statement, but don't know how to implement this:

this is what stores my list of event ids

List<int> ExcludedEvents; 

and this is my select statement (from an XML feed)

 var allEvents = from eventsList in xmlDoc.Elements("shows").Elements("Show") select new EventFeed() { EventName = eventsList.Attribute("Name").Value, EventSummary = eventsList.Attribute("ShortDesc").Value, EventDetails = eventsList.Attribute("LongDesc").Value, EventShowCode = eventsList.Attribute("Code").Value }; 

I want to select all events except events for which their eventId matches the value of EventShowCode

I looked at the except statement, but not sure how to implement it

+6
linq except
source share
1 answer

based on your code in question, it should look something like this ...

 var filteredEvents = allEvents.Where(myEvent => !ExcludedEvents.Contains(myEvent.EventShowCode)); 

Or, if you just want to apply it to the end of your select statement, just take this β€œWhere” and drop it right at the end of your selection from your previous query ...

 var filteredEvents = xmlDoc.Elements("shows").Elements("Show") .Select( new { EventName = eventsList.Attribute("Name").Value, EventSummary = eventsList.Attribute("ShortDesc").Value, EventDetails = eventsList.Attribute("LongDesc").Value, EventShowCode = eventsList.Attribute("Code").Value }) .Where(myEvent => !ExcludedEvents.Contains(myEvent.EventShowCode)); 
+4
source share

All Articles