我有一个Product
具有几个属性的类:
public class Product
{
public int id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public string ProdCountry { get; set; }
}
现在假设我有var products = List<Product>
并且我想过滤一些我事先不知道的特定属性值。所有{ propertyName, propertyValue }
对都必须匹配(所以 AND 关系):
Dictionary<string, string> properties = GetPropertiesFromClient(); //Key = propertyName, Value = propertyValue
List<Product> products = GetProductList();
foreach(var property in properties)
{
switch (property.Key)
{
case "Name": products = products.Where(p => p.Name == property.Value);
break;
case "Category": products = products.Where(p => p.Category == property.Value);
break;
case "ProdCountry": products = products. Where(p => p.ProdCountry == property.Value);
break;
}
}
该方法GetPropertiesFromClient()
总是返回一个Dictionary<string, string>
我事先不知道存储了哪些属性和多少的地方。
有什么快捷方式可以避免我使用 aswitch case
吗?就像是:
foreach(var property in properties)
{
products = products.Where(t => t.GetType().GetProperty(property.Key).GetValue(t, null) == property.Value);
}
这段代码应该工作(逻辑上),但我得到一个例外:
LINQ to Entities 无法识别方法 'System.Object GetValue(System.Object, System.Object[])' 方法,并且此方法无法转换为存储表达式。
我怎样才能实现我的目标?