【问题标题】:Linq contains operatorLinq 包含运算符
【发布时间】:2011-10-24 00:25:33
【问题描述】:

这很好用:

var q = (from c in db.tblLiteCategorySpecs where CategoryIDs.Contains(c.CategoryID) select c.SpecID).Distinct().ToList();
var qq = (from s in db.tblSpecifications where q.Contains(s.id) select s);

但是我现在需要在第一个查询中返回另一个字段:

var q = (from c in db.tblLiteCategorySpecs where CategoryIDs.Contains(c.CategoryID) select new { c.SpecID, c.FriendlyName }).Distinct().ToList();
var qq = (from s in db.tblSpecifications where q.Contains(s.id) select s);

所以q.contains 现在失败了,我需要它以某种方式处理q 查询SpecID 字段。有人知道怎么做吗?

【问题讨论】:

    标签: c# asp.net linq contains


    【解决方案1】:

    嗯,你可以试试

    var qq = from s in db.tblSpecifications
             where q.Select(x => x.SpecID).Contains(s.id)
             select s;
    

    换句话说,在使用Contains 之前投影结果。我不知道 SQL 会是什么样子。

    顺便说一句,我个人只是把它写成:

    var qq = db.tblSpecifications
               .Where(s => q.Select(x => x.SpecID).Contains(s.id));
    

    我只使用真正让事情变得更简单的查询表达式语法。我还强烈建议您在查询中使用多行 - 它确实有助于提高可读性。

    【讨论】:

      【解决方案2】:

      这是你想要的吗?

      var q = (from c in db.tblLiteCategorySpecs where CategoryIDs.Contains(c.CategoryID) select new { c.SpecID, c.FriendlyName }).Distinct().ToList();
      var qq = (from s in db.tblSpecifications where q.Any(c => c.SpecID == s.id) select s);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-04
        • 1970-01-01
        • 2012-07-28
        • 2019-04-09
        • 2020-10-28
        • 2010-11-01
        • 2017-02-05
        • 1970-01-01
        相关资源
        最近更新 更多