如何使用Linq和c#将属性与List进行比较?

本文关键字:string 比较 List Linq 何使用 属性 | 更新日期: 2023-09-27 18:14:29

我有一个代码,是过滤列表使用这样的代码..

    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可以工作,但我不能得到正确的语法

如何使用Linq和c#将属性与List<string>进行比较?

使用stringsToCompare.Contains:

var newListOfProducts = products.Where(p => stringsToCompare.Contains(p.MyProperty));

把它翻过来:

List<string> stringsToCompare = new List<string>() {"prop1","prop2","prop3"};
var newListOfProducts = products.Where(p=>stringsToCompare.Contains(p.MyProperty));               

我建议使用HashSet而不是List

var stringsToCompare = new HashSet<string>() {"prop1","prop2","prop3"};
var newListOfProducts = products.Where(p => stringsToCompare.Contains(p.MyProperty));