我有使用这样的代码过滤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");
Run Code Online (Sandbox Code Playgroud)
我的偏好是使用这样的语法......
List<string> stringsToCompare = new List<string>() {"prop1","prop2","prop3"};
var newListOfProducts = products.Where(p=>p.MyProperty.IsInList(stringsToCompare));
Run Code Online (Sandbox Code Playgroud)
这样我就可以动态构建stringToCompare而不是硬编码.
但是,尽管谷歌搜索了过去的半小时,但我无法弄清楚如何做到这一点.我认为Intersect或Union可以工作,但我无法正确使用语法.
翻转并使用stringsToCompare.Contains:
var newListOfProducts = products.Where(p => stringsToCompare.Contains(p.MyProperty));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
305 次 |
| 最近记录: |