您可以结合使用反射、循环遍历属性和动态 linq来构建 where 谓词来执行此操作。
下面是一个简单的例子作为起点/概念证明。
目前它null
用作指示我们不想要 where 子句的值,但如果您有一个值类型属性 (like int
),那么您可以添加一个属性 like[FilterIgnore]
或其他东西,并在您遍历属性时检查它。
创建一个新的控制台应用程序并用它替换 program.cs,然后将示例中的动态 linq 文件添加到项目中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
class MyObject
{
// Some properties
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public DateTime? PropertyC { get; set; }
static void Main(string[] args)
{
// Our repository
var list = new List<MyObject>() {
new MyObject() { PropertyA = "test"} ,
new MyObject() { PropertyB = "test"} ,
new MyObject() { PropertyC = DateTime.Today} ,
new MyObject() { PropertyC = DateTime.Today,
PropertyA = "test"}
};
// Loop through the filtered results
// (calling our GetByExample method with a
// new object with a property set)
foreach (var obj in
GetByExample(list,
new MyObject() { PropertyC = DateTime.Today }))
{
// Write some output so we can see it working
Console.WriteLine("Found object");
Console.WriteLine(obj.PropertyA);
Console.WriteLine(obj.PropertyB);
Console.WriteLine(obj.PropertyC);
}
// Wait for the user to press a key before we close
Console.ReadKey();
}
static IQueryable<MyObject> GetByExample(List<MyObject> objects,
MyObject filterObj)
{
// Create our query variable that we'll add to
var filteredObjects = objects.AsQueryable();
// Loop through each property on this object
foreach (var prop in filterObj.GetType().GetProperties())
{
// Get the value of this property
var propVal = prop.GetValue(filterObj, null);
if (propVal != null)
{
// If the property isn't null add a where clause
filteredObjects =
filteredObjects.Where(string.Format("{0} = @0",
prop.Name),
propVal);
}
}
return filteredObjects;
}
}