【问题标题】:Select only the parents where any of the children's names do not contain a specific string仅选择其中任何孩子的名字不包含特定字符串的父母
【发布时间】:2016-02-16 10:11:58
【问题描述】:

我正在使用 Linq 从上下文中检索数据。我试图只获取没有孙子AttributeItems 的父项CategoryAttributeItemDescriptions 的内部名称包含单词“Range -” 下面的代码是我目前所在的位置。

var query = from caid in context.CategoryAttributeItemDescriptions
                    join cai in context.CategoryAttributeItems on caid.Id  equals cai.CategoryAttributeItemDescriptionsId
                    join ai in context.AttributeItems on cai.AttributeId equals ai.Id
                    where caid.CategoryAttributeItems.Any(c => !c.AttributeItem.InternalName.Contains("Range -")) && caid.CategoryId ==element.Id
                    select caid;

问题在于返回的父母仍然与具有该内部名称的孙子有关系。有任何想法吗? 谢谢

【问题讨论】:

  • 尝试将 where 子句更改为 'where caid.CategoryAttributeItems.Any(c => !c.AttributeItem.InternalName.Contains("Range -")) && caid.CategoryId ==element.Id'
  • 基本上在 c.AttributeIte.... 之前添加感叹号。这意味着'Not'
  • 我可能在上面读错了,但你不是在 Any() 谓词中寻找 FOR 匹配,而不是排除??
  • 我添加了感叹号(愚蠢的错误),但是,它仍然只忽略所有孙子都使用这个内部名称的父母,而不是例如只有一个的父母。

标签: c# sql linq


【解决方案1】:

听起来像是错误的逻辑。

这个

caid.CategoryAttributeItems.Any(c => !c.AttributeItem.InternalName.Contains("Range -"))

根据你的要求应该是

!caid.CategoryAttributeItems.Any(c => c.AttributeItem.InternalName.Contains("Range -"))
^                            ^         ^
do not                       have      with an internal name containing the word "Range -"

【讨论】:

  • 感谢您的回复!但是,问题是,如果其中一个孙子包含名称“Range -”,则父代不打折,仍会添加到查询中。如果有孙子有这个名字,我想完全忽略父母。
  • 我没有分析整个查询,但现在我看到joins 是多余的,并且将结果集相乘,因此您最好将它们删除。虽然这是另一个问题。 parent 你的意思是 caid 和孙子 'caid.CategoryAttributeItems, right? Are you sure you applied exactly the suggestion in the answer? !Any(Contains())` 应该做你想做的事。
  • caid 确实是父母,attributeItems 是孙子女。我注意到结果是重复的,所以使用 Distinct。但是,此时为时已晚,因为已添加带有“范围”的属性项。
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 2016-01-02
  • 1970-01-01
  • 2019-06-10
  • 2014-03-01
  • 1970-01-01
相关资源
最近更新 更多