您可以使用反射的組合來遍歷您的屬性,並使用dynamic linq來構建Where謂詞。
下面是一個簡單的例子,作爲一個起點/概念驗證。
目前,它採用null
作爲值,表明我們不想where子句,但如果你有一個值類型屬性(如int
),那麼你可以添加屬性像[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;
}
}
你不會需要多個。哪裏查詢,只有一個在其中指定您需要匹配哪些屬性,例如.Where(k => k.Prop1 == given.Prop1 && k.Prop2 == given.Prop2 ..)。你也可以把它放在一個委託中,並把它作爲參數發送。 –
可能是反射和動態linq的組合。你會遍歷你的對象的屬性不是null(或者一些「忽略」值),不斷地使用動態linq添加where子句。 –
你打算指出哪些字段要忽略以及使用哪些字段,因爲你有不可空字段? –