【问题标题】:Linq/SQL Query Sorting for Multiple LIKE conditions多个 LIKE 条件的 Linq/SQL 查询排序
【发布时间】:2010-10-10 12:29:55
【问题描述】:

我在数据库中有一个表,其结构如下:

Date
{
    ID,
    Username,
    Label,
    DateTime
}

我希望能够在 linq 中对 Username 和 Label 列执行基本的 .Contains 搜索,但有一个问题。我想按 LIKE 匹配的数量排序。这就是我的意思:

如果我有 Data = {ID=1,Username="Shawn",Label="Whatever",DateTime=1/1/2010} 的实例

1) 如果我搜索 User="awn" 和 Label="What",结果的匹配顺序为 2。

2a) User="haw" 和 Label="cat" 的匹配顺序为 1

2b) User="Doug" 和 Label="ever" 的匹配顺序为 1

3) User="Chris" 和 Label="Fish" 的匹配顺序为 0

我希望能够按匹配顺序排序,其中 2 的顺序优于 1,然后在每个匹配顺序中我想按日期排序。

理想情况下,我希望能够在 linq 中执行此操作,但我愿意给直接 SQL 代码一个机会。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    你能不能试试:

    from row in db.Dates
    let x = row.UserName.Contains(username) ? 1 : 0
           + row.Label.Contains(label) ? 1 : 0
    order by x descending
    select new {row.Id, row.UserName, row.Label,
         Value = x};
    

    如果不是,在 TSQL 中同样使用 CASE WHEN ... THEN 1 ELSE 0 END

    【讨论】:

    • 这看起来很可靠。我总是忘记能够添加 linq 查询。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多