如何动态组合linq查询?

时间:2013-01-28 06:25:58

标签: c# sql sql-server linq linq-to-sql

假设我有一个表,其中包含字符串(nvarchar)列中的格式化值。这些值应该是由一些const符号分隔的字符串(让它是一个分号;)。例如,

12;0;5;dog //four values separated by a semi-colon

053 //if there is only one value, no semi-colon at the end

分隔符始终是分隔符,它不能是值的一部分。

我需要检查该表中是否已有一行,其中包含该列中的值列表,其中至少包含一个指定的项。换句话说,我有一个值列表:

List<string> list = new List<string>() { "somevalue1", "somevalue2" };

分隔符:

string separator = ";";

我需要编写一个linq-to-sql查询来执行此操作:

select ... from sometable
where Value='somevalue1' or Value like 'somevalue1;%' or
      Value like '%;somevalue1' or Value like '%;somevalue1;%'

   or Value='somevalue2' or Value like 'somevalue2;%' or 
      Value like '%;somevalue2' or Value like '%;somevalue2;%'

应该提到的是,任何搜索的值都可以包含另一个。也就是说,我可能正在搜索5,而某些行可能包含1;15;55。这样的行必须​​才能匹配。虽然...;5;...或仅5,或5;......;5是匹配。

使用linq-to sql我知道如何进行以下类型的查询:

select ... from sometable where (... or ... or ...) and (... or ...) ...

IQueryable<SomeTable> query = dc.SomeTable;
foreach (string l in list)
{
    string s = l;
    query = query.Where(b => b.Value.StartsWith(s + separator) ||
                             b.Value.EndsWith(separator + s) ||
                             b.Value.Contains(separator + s + separator) ||
                             b.Value.Equals(s));
}
if (query.Any()) {/*...*/}

显然,Where语句在生成的sql查询中与AND连接,而我到处都需要OR

那么有没有办法在C#代码中获取我需要的查询?或者唯一的方法是使用手写的查询和DataContext.ExecuteQuery Method来做到这一点?

2 个答案:

答案 0 :(得分:3)

我想UNION符合您的需求:

IQueryable<SomeTable> baseQuery = dc.SomeTable;
IQueryable<SomeTable> query = new List<SomeTable>().AsQueryable();
foreach (string l in list)
{
    string s = l;

    query.Union(baseQuery.Where(b => b.Value.StartsWith(s + separator) ||
                             b.Value.EndsWith(separator + s) ||
                             b.Value.Contains(separator + s + separator) ||
                             b.Value.Equals(s)));
}
if (query.Any()) {/*...*/}

答案 1 :(得分:3)

public static Expression<Func<T, bool>> OrTheseFiltersTogether<T>(
  this IEnumerable<Expression<Func<T, bool>>> filters)
{
    Expression<Func<T, bool>> firstFilter = filters.FirstOrDefault();
    if (firstFilter == null)
    {
        Expression<Func<T, bool>> alwaysTrue = x => true;
        return alwaysTrue;
    }

    var body = firstFilter.Body;
    var param = firstFilter.Parameters.ToArray();
    foreach (var nextFilter in filters.Skip(1))
    {
        var nextBody = Expression.Invoke(nextFilter, param);
        body = Expression.OrElse(body, nextBody);
    }
    Expression<Func<T, bool>> result = Expression.Lambda<Func<T, bool>>(body, param);
    return result;
}

因此,您可以从输入集轻松构建过滤器列表:

List<string> list = new List<string>() { "somevalue1", "somevalue2" };
List<Expression<Func<SomeTable, bool>>> equalsFilters = list
  .Select(s => row => row.Value == s).ToList();
List<Expression<Func<SomeTable, bool>>> startsWithFilters = list
  .Select(s => row => row.Value.StartsWith(s + ";")).ToList();
List<Expression<Func<SomeTable, bool>>> endsWithFilters = list
  .Select(s => row => row.Value.EndsWith(";" + s).ToList();
List<Expression<Func<SomeTable, bool>>> middleFilters = list
  .Select(s => row => row.Value.Contains(";" + s + ";")).ToList();

Expression<Func<SomeTable, bool>> theFilter = OrTheseFiltersTogether(
  equalsFilters.Concat(startsWithFilters).Concat(endsWithFilters).Concat(middleFilters)
);

query = query.Where(theFilter);