我有两个IQueryables:
public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery)
{
return queryable.Where(x => x.Code.StartsWith(searchQuery.ToUpper()));
}
public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery)
{
return queryable.Where(x => x.Name.ToLower().Contains(searchQuery.ToLower()));
}
我想创建另一个IQueryable,它将两个查询组合为OR,例如
public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
// return SearchByName(searchQuery) OR SearchByCode(searchQuery)
}
我宁愿避免重复代码,所以我想重用现有的可查询而不是重写一个新的lambda表达式,如Where(x=> x.Code.StartsWith.... || x.Name.Contains.....)
答案 0 :(得分:5)
你可能会。两者结合在一起
public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
return SearchByName(searchQuery).Union(SearchByCode(searchQuery))
}
答案 1 :(得分:1)
根据您希望能够重用的代码,这可能是您不重复查询条件内部工作的替代方法:
private static Func<Counterparty, string, bool> CodeStartsWith = (x, searchQuery) => x.Code.StartsWith(searchQuery.ToUpper());
private static Func<Counterparty, string, bool> NameContains = (x, searchQuery) => x.Name.Contains(searchQuery.ToLower());
public static IQueryable<Counterparty> SearchByCode(this IQueryable<Counterparty> queryable, string searchQuery)
{
return queryable.Where(x => CodeStartsWith(x, searchQuery));
}
public static IQueryable<Counterparty> SearchByName(this IQueryable<Counterparty> queryable, string searchQuery)
{
return queryable.Where(x => NameContains(x, searchQuery));
}
public static IQueryable<Counterparty> SearchByCodeOrName(this IQueryable<Counterparty> queryable, string searchQuery)
{
return queryable.Where(x => NameContains(x, searchQuery) || CodeStartsWith(x, searchQuery));
}