保持类型安全!
最好构造一个返回良好属性的函数列表,而不是声明一个字符串变量,如果有一天您想更改列名,该变量将失败:
public class Customer { public string FirstName; public string LastName;}
public class CustomerFilter { public Func<Customer, string> Selector; public string Filter; }
[TestMethod()]
public void DynamicFilterTest()
{
var jonSkeet = new Customer() { FirstName = "Jon", LastName = "Skeet" };
var joelOnSoftware = new Customer() { FirstName = "Joel", LastName = "OnSoftware" };
var customers = new List<Customer>() { jonSkeet, joelOnSoftware };
var jonSkeetFilters = new List<CustomerFilter>() {
new CustomerFilter() { Selector = c => c.LastName, Filter = "Skeet" },
new CustomerFilter() { Selector = c => c.FirstName, Filter = "Jon" }};
var query = customers.AsEnumerable();
foreach (var filter in jonSkeetFilters)
{
query = query.Where(c => filter.Selector.Invoke(c) == filter.Filter);
}
var result = query.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(jonSkeet, result.Single());
}
然后,您可以轻松地重构以对任何实体使用相同的模式:
public class WhereClause<T>
{
private readonly Func<T, string> _selector;
public Func<T, string> Selector { get { return _selector; } }
private readonly string _value;
public string Value { get { return _value; } }
public WhereClause(Func<T, string> selector, string value)
{
this._selector = selector;
this._value = value;
}
/// <summary>
/// Append the where clause to the given query
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public IEnumerable<T> AppendTo(IEnumerable<T> query)
{
return query.Where(c => this.Selector.Invoke(c) == this.Value);
}
/// <summary>
/// Append the wheres clauses to the given query
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public static IEnumerable<T> AppendTo(IEnumerable<T> query, IEnumerable<WhereClause<T>> wheres)
{
var filteredQuery = query;
foreach (var where in wheres)
{
filteredQuery = where.AppendTo(filteredQuery);
}
return filteredQuery;
}
}
[TestClass]
public class WhereClauseTests
{
public class Customer { public string FirstName; public string LastName;}
[TestMethod()]
public void WhereClauseTest()
{
var jonSkeet = new Customer() { FirstName = "Jon", LastName = "Skeet" };
var joelOnSoftware = new Customer() { FirstName = "Joel", LastName = "OnSoftware" };
var customers = new List<Customer>() { jonSkeet, joelOnSoftware };
var jonSkeetWheres = new List<WhereClause<Customer>>() {
new WhereClause<Customer>(c => c.LastName, "Skeet"),
new WhereClause<Customer>(c => c.FirstName, "Jon" )
};
var query = WhereClause<Customer>.AppendTo(customers, jonSkeetWheres);
var result = query.ToList();
Assert.AreEqual(1, result.Count);
Assert.AreEqual(jonSkeet, result.Single());
}
}