리플렉션을 사용하여 속성을 반복하고 dynamic linq을 사용하여 where 조건자를 작성할 수 있습니다.
다음은 출발점/개념 증명의 간단한 예입니다.
현재 우리가 where 절을 원하지 않는 것을 나타내는 값으로 null
를 사용하지만, 당신이 값 형식 속성을 가지고있는 경우 (int
를 같은) 당신은 [FilterIgnore]
이나 뭐 같은 속성을 추가하고 확인할 수 있습니다 때 당신에게 루프가 속성을 통해.
다음 프로젝트에 샘플에서 동적 LINQ 파일을 추가 새 콘솔 응용 프로그램을 확인하고이 함께 program.cs을 바꿉니다하는,
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의 조합. 널 (또는 일부 "무시"값)이 아닌 객체의 속성을 반복하면서 동적 linq을 사용하여 where 절을 계속 추가합니다. –
nullable 필드가 없기 때문에 무시할 필드와 사용할 필드를 어떻게 지정 하시겠습니까? –