如何使用 linq 检查 class 的 属性(classes 的 collection/enumeration)是否与另一个集合中的项目匹配?
How to check if the property of a class(collection/enumeration of classes) matches to an item from another collection using linq?
我有一个 class 产品
public Guid Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
颜色可以是字符串,如“Blue, Red, Green”或“Red, Brown”等
我有这些 class 的集合或枚举,例如
Ienumerable<Product> Products
我还有另一个颜色字符串集合,例如
List<string> colorsForFiltering = new List<string>() { Blue, Yellow, Brown}
如何使用颜色 属性 抛出 linq 查询来过滤产品?
我尝试了几种选择,包括
Products = Products.Where(x => colorsForFiltering.Contains(x.Color));
和许多其他人。我知道这个查询是错误的。我确定我可以使用循环解决这个问题。但我想知道是否可以使用 linq 来做到这一点。不幸的是我找不到答案。提前致谢!
Johnathan Barclay 在评论中解决了这个问题
x => colorsForFiltering.Any(x.Color.Contains)
我只是用了 All 而不是 Any
理想情况下,您应该将 Color
更改为 IEnumerable<string>
,但您可以使用以下内容:
Products = Products.Where(x => colorsForFiltering.Intersect(x.Color.Split(',', StringSplitOptions.TrimEntries).Any());
请注意,这几乎肯定无法翻译成 SQL,因此您必须在记忆中完成。 SQL 可翻译的替代方法是循环过滤颜色:
var results = colorsForFiltering.SelectMany(c=>
Products.Where(x => x.Color.Contains(c))
);
这也不是万无一失的,因为如果你有任何颜色是另一种颜色的子串(例如“蓝-绿”),那么 Contains
将匹配子串,但它可以翻译成 SQL
我有一个 class 产品
public Guid Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
颜色可以是字符串,如“Blue, Red, Green”或“Red, Brown”等
我有这些 class 的集合或枚举,例如
Ienumerable<Product> Products
我还有另一个颜色字符串集合,例如
List<string> colorsForFiltering = new List<string>() { Blue, Yellow, Brown}
如何使用颜色 属性 抛出 linq 查询来过滤产品? 我尝试了几种选择,包括
Products = Products.Where(x => colorsForFiltering.Contains(x.Color));
和许多其他人。我知道这个查询是错误的。我确定我可以使用循环解决这个问题。但我想知道是否可以使用 linq 来做到这一点。不幸的是我找不到答案。提前致谢!
Johnathan Barclay 在评论中解决了这个问题
x => colorsForFiltering.Any(x.Color.Contains)
我只是用了 All 而不是 Any
理想情况下,您应该将 Color
更改为 IEnumerable<string>
,但您可以使用以下内容:
Products = Products.Where(x => colorsForFiltering.Intersect(x.Color.Split(',', StringSplitOptions.TrimEntries).Any());
请注意,这几乎肯定无法翻译成 SQL,因此您必须在记忆中完成。 SQL 可翻译的替代方法是循环过滤颜色:
var results = colorsForFiltering.SelectMany(c=>
Products.Where(x => x.Color.Contains(c))
);
这也不是万无一失的,因为如果你有任何颜色是另一种颜色的子串(例如“蓝-绿”),那么 Contains
将匹配子串,但它可以翻译成 SQL