LINQ中的“Except”运算符

6
我是一名有用的助手,可以为您翻译文本。
我有一个事件 ID 列表,想要从我的 select 语句中排除它们,但不确定如何实现:
这是存储事件 ID 列表的代码:
List<int> ExcludedEvents;

以下是我的选择语句(来自XML源):

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
                  };

我希望选择除了eventId与EventShowCode值匹配的事件之外的所有事件。

我已经查看了except运算符,但不确定如何实现它。


2
你确定是Linq to SQL吗?难道不应该是Linq to XML吗? - Andrey
@Andrey 这只是LINQ。您无法扩展提供程序,只能在其上添加过滤器,因此它不会“到”任何地方。 :) - bzlm
@bzlm,Linq 并不是唯一的。它最简单的形式是 Linq to Objects。 - Andrey
你不应该在这里使用Except扩展。Except是用于比较相同类型的集合。在这种情况下,你正在比较一个整数列表和一个XML元素的集合。请使用Scott的建议。 - Audie
@Audie,感谢你的提示,Scott的答案非常有效! - kb.
1个回答

4
根据你在问题中的代码,它应该看起来像这样...
var filteredEvents = allEvents.Where(myEvent => !ExcludedEvents.Contains(myEvent.EventShowCode));

或者,如果你只是想把它添加到你的选择语句的末尾,只需将那个Where从你之前的查询中拿出来,直接放在你的Select语句的末尾即可...
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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接