【问题标题】:Filtering using LINQ to SQL使用 LINQ to SQL 进行过滤
【发布时间】:2012-01-21 09:01:34
【问题描述】:

我有一张如下表

ID Code  
1  9198  
2  9194  
3  91989  
4  91900  
5  918907

我现在已经准备好了这张桌子我想做的是 就像我有一个值 919898989898 并且从这个值中我从表中得到以下结果

Result  
ID Code  
1  9198

如果我通过 9198900015536​​3 那么结果应该是

Result  
ID Code  
3  91989  

我希望 linq to sql 中的这种查询将匹配给定值的最大字符与数据库表匹配。

【问题讨论】:

  • 所以你想要 C# 中的 Code.StartsWith(x) 或 SQL 中的 Code LIKE '%' + x 的模拟?
  • 请记住,任何 LINQ to SQL 调用都应该可翻译到 SQL,否则您需要将所有数据加载到内存中并由 LINQ to Objects 处理

标签: .net sql linq linq-to-sql


【解决方案1】:

假设代码实际上是一个 VARCHAR,您可以尝试:

var input = "919898989898";
var allMatches = from item in dbContext
                 where input.StartsWith(item.Code)
                 orderby item.Code.Length descending
                 select item;
var longestMatch = allMatches.FirstOrDefault();

或者将查询放入单个语句中,使用点表示法而不是查询表达式:

var longestMatch = dbContext.Where(item => input.StartsWith(item.Code))
                            .OrderByDescending(item => item.Code.Length)
                            .FirstOrDefault();

现在这些查询逻辑上没问题 - 但您必须尝试它们以查看它们是否正确转换为 SQL。

【讨论】:

  • 我试过了,得到以下错误。 String.StartsWith 方法仅支持可以在客户端上计算的参数。
  • @Ronak:在那种情况下,我什至不确定它是否可以在 LINQ to SQL 中完成。
【解决方案2】:
var query = from item in dbContext
     where item.Code == input.Substring(0, item.Code.Length)
     orderby item.Code.Length descending
     select item;

var longestMatch = query.FirstOrDefault();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多