Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ "Except" Operator

Tags:

linq

except

i have a list of event Ids that i want to be excluded from my select statement, but no sure 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 for the events that have their eventId matching the EventShowCode value

i have looked at the except operator, but not sure how to implement it

like image 736
kb. Avatar asked Apr 12 '10 14:04

kb.


People also ask

What is except in LINQ?

In LINQ, the Except method or operator is used to return only the elements from the first collection, which are not present in the second collection.

How do you use list except?

Get the difference between two arrays using the Except() method. The following are the two arrays. int[] arr = { 9, 12, 15, 20, 35, 40, 55, 67, 88, 92 }; int[] arr2 = { 20, 35 }; To get the difference, use Except() method that returns the first list, except the elements in the second list.

What is used except method?

The except() method is used to return all items in the given collection except the specified keys.

What is use of except method Java?

The Except operator returns the set difference. Or in other words, we can say that it returns the set or collection which contain the elements that do not appear in the second collection or set.


1 Answers

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

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

Or, if you just wanted to tack it on to the end of your select statement, just take that Where and drop it right at the end of your Select 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));
like image 186
Scott Ivey Avatar answered Sep 29 '22 12:09

Scott Ivey