【问题标题】:Linq to DataSetLinq 到数据集
【发布时间】:2015-08-08 23:22:52
【问题描述】:

我想挑选所有不是部门老板的卖家。

我怎样才能做到这一点?在下面的这个查询中,只有作为部门老板的卖家被选中,我想要它的反面。

我的查询:

var query = db.Sellers
            .Join(db.Departments,
            s => s.Id,
            d => d.BossId,
            (s, d) => new { Seller = s, Department = d })
            .Where(a => a.Seller.Id == a.Department.BossId) ????
            .Select(x => x.Seller).ToList();

在“Where”部分,我试过a => a.Seller.Id != a.Department.BossId,但是错了我有3个不是老板的卖家。

我也试过这种方式:

var listNonBoss = (from s in db.Sellers
                  join d in db.Departments on s.Id equals d.BossId
                  select s.Id).ToList();

我想要这些查询的反面。

【问题讨论】:

    标签: c# .net asp.net-mvc linq linq-to-sql


    【解决方案1】:

    您的代码中的Join 将进行内部连接,这意味着它将过滤掉没有老板的卖家。

    相反,你可以做一个外部连接,然后删除那些有老板的人。在流利的 LINQ 中,外部连接是通过执行 GroupJoin 然后 SelectMany 来完成的。

    类似这样的:

    var query = db.Sellers
        .GroupJoin(db.Departments, s => s.Id, d => d.BossId, (s, d) => new { Seller = s, Department = d })
        .SelectMany(x => x.d.DefaultIfEmpty(), (seller, department) => new { s.seller, department})
        .Where(a => a.department.BossId == null)
        .Select(x => x.Seller).ToList();
    

    或者,使用查询语法:

    var listNonBoss = (from s in db.Sellers
                      join d in db.Departments on s.Id equals d.BossId into joinedTable
                      from jt in joinedTable.DefaultIfEmpty()
                      where jt.BossId == null
                      select s.Id).ToList();
    

    【讨论】:

      【解决方案2】:

      有时将其分解为多个步骤会更容易。

      首先,获取所有boss ID的集合:

      var bossIDs = db.Departments.Select(x => x.BossId);
      

      然后获取该集合中ID为的所有卖家:

      var listNonBoss = db.Sellers.Where(x => !bossIDs.Contains(x.Id)).ToList();
      

      【讨论】:

      • 还有什么比它更简单的呢?非常感谢,非常非常清晰的解决方案。
      猜你喜欢
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多