我使用简单的扩展方法和规范模式实现了这一点,适用于 System.Linq.IQueryable 列表。
public interface IFilter<in T>
{
bool MatchFilter(T o);
}
public static class FilterExtension
{
public static IQueryable<T> Filter<T>(this IQueryable<T> query, IFilter<T> filter)
{
return query.Where(x => filter.MatchFilter(x));
}
}
简单的示例类和 IFilter 实现:
public class Organization
{
public string Name { get; set; }
public string Code { get; set; }
public Address Address { get; set; }
public Organization(string name, string code, string city, string country)
{
Name = name;
Code = code;
Address = new Address(city, country);
}
}
public class Address
{
public Address(string city, string country)
{
City = city;
Country = country;
}
public string City { get; set; }
public string Country { get; set; }
}
public class GenericOrganizationFilter : IFilter<Organization>
{
public string FilterString { get; set; }
public GenericOrganizationFilter(string filterString)
{
FilterString = filterString;
}
public bool MatchFilter(Organization o)
{
return
(o.Name != null && o.Name.Contains(FilterString)) ||
(o.Code != null && o.Code.Contains(FilterString)) ||
(o.Address != null && o.Address.City != null && o.Address.City.Contains(FilterString)) ||
(o.Address != null && o.Address.Country != null && o.Address.Country.Contains(FilterString));
}
}
用法:
IFilter<Organization> filter = new GenericOrganizationFilter("search string");
//Assuming queryable is an instance of IQueryable<Organization>.
IQueryable<Organization> filtered = queryable.Filter(filter);