public class Sample
{
public int Id { get; set; }
public string Description { get; set; }
public DateTime EffectiveDate { get; set; }
}
IEnumberable<Sample> sampleList;
//Populate the list
public class Sample
{
public int Id { get; set; }
public string Description { get; set; }
public DateTime EffectiveDate { get; set; }
}
IEnumberable<Sample> sampleList;
//Populate the list
现在我想通过“Id”属性有时候过滤列表,有时候是“Description”属性。只是想将属性名称(filterColumn)和属性值(filterValue)都作为字符串传递。C#Linq筛选器IEnumerable动态属性和值
我试过如下:
IEnumerable<Sample> result = sampleList.Where(x => x.GetType().GetProperty(filterColumn).Name == filterValue);
和
string whereQuery = string.Format(" {0} = \"{1}\"", filterColumn, filterValue);
IEnumerable<Sample> result = sampleList.AsQueryable().Where(whereQuery);
第二个选项的作品,如果我通过了filterColumn作为 “说明”,但抛出的字符串和INT之间incomptable '=' 操作当“Id”作为filterColumn传递并出现一些filterValue(如“1”)时出错。
感谢任何帮助。谢谢
您的第一个人正在检查它,*属性名称*与指定的属性值相同。您需要在PropertyInfo上调用'.GetValue(x,null)'...然后你想使用'Equals'而不是'=='。 –
你为什么要做'.AsQueryable()'? – Enigmativity