我有使用这样的代码过滤List的代码..
List<Product> products = new List<Product>() { /*<INIT THE COLLECTION>*/ }
//get the ones you need.
var newListOfProducts = products.Where(p=>p.MyProperty == "prop1" || p.MyProperty == "prop2" || p.MyProperty == "prop3");
我的偏好是使用这样的语法......
List<string> stringsToCompare = new List<string>() {"prop1","prop2","prop3"};
var newListOfProducts = products.Where(p=>p.MyProperty.IsInList(stringsToCompare));
这样我就可以动态构建stringToCompare而不是硬编码。
但是,尽管谷歌搜索了过去的半小时,但我无法弄清楚如何做到这一点。我认为Intersect或Union可以工作,但我无法正确使用语法。
答案 0 :(得分:5)
翻转并使用stringsToCompare.Contains
:
var newListOfProducts = products.Where(p => stringsToCompare.Contains(p.MyProperty));
答案 1 :(得分:1)
只需翻转它:
List<string> stringsToCompare = new List<string>() {"prop1","prop2","prop3"};
var newListOfProducts = products.Where(p=>stringsToCompare.Contains(p.MyProperty));
答案 2 :(得分:0)
我建议使用HashSet
代替List
var stringsToCompare = new HashSet<string>() {"prop1","prop2","prop3"};
var newListOfProducts = products.Where(p => stringsToCompare.Contains(p.MyProperty));