【问题标题】:How do I write a contains statement in linq?如何在 linq 中编写包含语句?
【发布时间】:2016-01-07 21:47:51
【问题描述】:

我想选择任何选定字段为 1 的记录。

decimal myNumber = 1;
query = from q in query where myNumber.Contains(q.trial, q.score, q.id) select q;

我会在 sql 中写

select trial, score, id
from query q
where 1 in (q.trial, q.score, q.id)

如何使用 linq 复制 sql?

【问题讨论】:

    标签: sql linq contains


    【解决方案1】:

    您可以使用array 和Contains 方法作为示例:

    var query = from q in query
                where new[]{q.trial, q.score, q.id}.Contains(myNumber)  
                select q;
    

    相反,当您有许多值并且需要与单个列进行比较时,您可以执行以下操作:

    var myValues = new[] {1, 2, 3, 4, 5};
    var query = from q in query
                where myValues.Contains(q.trial)  
                select q;
    

    【讨论】:

    • 如果不将new[]{q.trial, q.score, q.id} 放在括号中,第一个示例是否有效?
    • @ code4life - 好吧,我会... Contains 不会在您这样编写时出现在 LinqPad 的 Intellisense 中,所以我认为它可能不起作用。但我还是按了全能的F5键。你知道什么...每天都学习新东西。
    【解决方案2】:

    详细阐述@Felipe 的帖子:

    var found = from q in query
        let arr = new []{ q.trial, q.score, q.id}
        where arr.Contains(1)
        select q;
    

    编辑: 看起来@Felipe 更新了他的帖子以使用动态创建的数组。我将留下我的帖子来演示 LINQ 查询 (let) 中变量的用法。这对于偶尔的情况很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-12
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 2013-12-19
      • 2011-12-31
      • 2020-01-19
      相关资源
      最近更新 更多