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

喜夏-厌秋 提交于 2019-12-22 01:58:46

问题


This seems like it would be easy enough

var orx = gg.Where(x=>x.ProductAttributes.Any (pa =>pa.AttributeId == "home"));

returns gg when product attributes has a value of "home"

I need it to return where and gg has product attribute values from an array i.e.

var orx = gg.Where(x=>x.ProductAttributes.Any (pa =>pa.AttributeId in "home,work"));

回答1:


what about...

string[] values = new string[] { "home", "work" };
var orx = gg.Where(x => x.ProductAttributes.Any(pa => values.Contains(pa.AttributeId));

or even "home,work".Contains(pa.AttributeId) should work, if your list is as reliable as your example. (I by no mean recommend this unless you can ensure that AttributeId will not be a substring of any of the list words.. such as "me")




回答2:


Using Enumerable.Contains():

var orx = gg.Where(x => x.ProductAttributes
                        .Any(pa =>
                             array.Containspa(pa.AttributeId));

var orx = gg.Where(x => x.ProductAttributes
                        .Any(pa =>
                             "home, work".Split(',').Contains(pa.AttributeId));


来源:https://stackoverflow.com/questions/7890117/linq-how-to-select-a-parent-with-a-child-collection-that-contains-one-or-many-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!