【问题标题】:LINQ "Except" OperatorLINQ“除外”运算符
【发布时间】:2011-02-07 00:52:59
【问题描述】:

我有一个要从我的选择语句中排除的事件 ID 列表,但不知道如何实现:

这是存储我的事件 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 运算符,但不知道如何实现它

【问题讨论】:

  • 您确定 Linq to SQL 吗?不是 Linq to XML 吗?
  • @Andrey 这只是 LINQ。您不能扩展提供者,只能在其之上添加过滤,因此它不是“对”任何东西。 :)
  • @bzlm 不仅仅是 Linq。最简单的形式是 Linq to Objects。
  • 你不想在这里使用 except 扩展。除非您比较相同类型的集合。在本例中,您将整数列表与 XML 元素的集合进行比较。使用 Scott 的建议。
  • @Audie,感谢您的提示,scotts 的回答很有效!

标签: linq except


【解决方案1】:

根据您在问题中的代码,它应该看起来像这样......

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

或者,如果您只是想将其添加到您的 select 语句的末尾,只需将其放在 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));

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    相关资源
    最近更新 更多