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