【问题标题】:linq how to select a parent with a child collection that contains all of an array (or list) of valueslinq 如何选择具有包含所有值数组(或列表)的子集合的父级
【发布时间】:2011-10-25 15:26:09
【问题描述】:

类似于linq how to select a parent with a child collection that contains one or many of an array (or list) of values

当集合应该包含数组中的所有值时,如何过滤

var andAttributes = "super-quiet,electric-start".Split(',');

var andx = gg.Where(x => x.ProductAttributes.All(pa => andAttributes.Contains(pa.AttributeId)));

上面的方法似乎可行,但似乎没有。

对于给定的示例,productAttributes 是一个通用列表,可能包含 1 个或多个特定值。

在英语中,我只想选择productAttributes 集合中同时包含超静音和电启动值的对象。

此表达式的作用类似于 OR 语句

var orx = gg.Where(x => x.ProductAttributes.Any(pa => orAttributes.Contains(pa.AttributeId)));

【问题讨论】:

  • ProductAttributes 包含什么?在什么情况下它不能获取正确的结果?一般来说,All 似乎是您想要的方法,但如果不了解您的数据的更多信息,则很难进一步提供帮助。

标签: c# linq collections linq-to-objects


【解决方案1】:

在英语中,我只想选择同时包含 productAttributes 中的超静音和电启动值 收藏。

您现有的查询正在过滤其所有产品属性都包含在测试集合中的对象。但您似乎想要反过来,即过滤 test-collection 中的所有属性都包含在其产品属性中的对象。

var filteredGGs = from obj in gg                  
                  let objAttribIds = obj.ProductAttributes
                                        .Select(pa => pa.AttributeId)

                  where !andAttributes.Except(objAttribIds).Any()

                  select obj;

另一方面,请尝试更好地命名您的变量,以便人们能够更好地理解您的意图。

【讨论】:

  • 我很欣赏这个答案的努力。它返回的正是我所期望的。我正在尝试使用 intersect 的路线,但我认为这个解决方案对于正在发生的事情更清楚一些。我为奇怪的 var 名称道歉,这是我粘贴的快速 linqpad 代码,但是在 gg 中实际上对我有意义。 ;)
猜你喜欢
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 2011-11-06
  • 2012-09-28
  • 2014-02-09
  • 2012-02-11
相关资源
最近更新 更多