static List<T> Filter<T>(List<T> source, string expresion) where T:class,new()
{
var propertys = typeof(T).GetProperties();
var resultList = new List<T>();
using (DataTable dt = new DataTable())
{
foreach (var prop in propertys)
{
var type = prop.PropertyType;
dt.Columns.Add(prop.Name, type);
}
foreach (var model in source)
{
var dataRow= dt.NewRow();
foreach (var prop in propertys)
{
dataRow[prop.Name]= prop.GetValue(model, null);
}
dt.Rows.Add(dataRow);
}
DataRow[] rows = dt.Select(expresion);
if (rows != null && rows.Length > 0)
{
foreach (var row in rows)
{
var instance = new T();
foreach (var prop in propertys)
{
prop.SetValue(instance, row[prop.Name], null);
}
resultList.Add(instance);
}
}
}
return resultList;
}
C# DataTable按列过滤通用函数
最新推荐文章于 2025-05-28 16:30:24 发布