有没有办法将下面的两种方法合并到一个动态方法中,根据用户输入调用LINQ where子句中的相应属性? 我想过做像
这样的事情var prop = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name.ToLower()));
然后在LINQ x => x.{prop} == name
里面做这样的事情,不确定是否存在这样的语法
public void FilterByName(string name)
{
var data = new InfoCollection().Data;
var result = data.Where(x => x.State == name)
Console.WriteLine(result);
}
public void FilterByCar(string car)
{
var data = new InfoCollection().Data;
var result = data.Where(x=> x.Car == car)
Console.WriteLine(result);
}
switch(searchByString)
{
case "name":
FilterByName(name)
break;
case "car":
FilterByCar(car)
break;
defualt:
break;
}
答案 0 :(得分:2)
尝试这样的事情
public void Filter(string column, string value)
{
var data = new InfoCollection().Data;
//get the column to filter
PropertyInfo property = data[0].GetType().GetProperty(column);
//filter getting dinamically the column
var result = data.Where(x => property.GetValue(x, null) == value);
Console.WriteLine(result);
}