【问题标题】:LINQ Join with where conditionLINQ Join with where 条件
【发布时间】:2015-05-13 15:33:32
【问题描述】:

我可以使用 LINQ 的 Join 和 Lambda 表示法没问题,但我不知道如何添加 where 条件。

var q = query.Join(context.CustomerIds,
    x => x.CustomerId,
    y => y.CustomerId,
    (x, y) => new CustomerLookupResult()
    {
        dob = x.DateOfBirth.ToString(),
        forenames = x.Forenames,
        surname = x.Surname,
        loyaltyNo = y.Identifier,
        customerId = x.CustomerId
    });

我要加入的第一个表在其Identifier 列中包含loyaltyNo,但在同一列中还包含其他信息,因此使用第二列IdentifierTypeCode 来允许过滤。

那么我现在如何像在 SQL 中一样添加.Where(x => x.IdentifierTypeCode == "LOYALTY")。将 this 附加到 end 是指新对象。

【问题讨论】:

  • 在不知道这两个列表的内容的情况下,类似:var q = query.Join(context.CustomerIds.Where(x=>x.IdentifierTypeCode=="LOYALTY"),
  • 当然,就是这样!谢谢你。把它作为答案,我会接受的。
  • 我认为在 lamdas msdn.microsoft.com/en-us/library/bb397947.aspx 上使用查询语法编写时加入 LINQ 更容易理解

标签: asp.net-mvc linq entity-framework lambda


【解决方案1】:

您可以在加入之前申请您的Where

var q = customerLoyalties
        .Where(x => x.IdentifierTypeCode == "LOYALTY")
        .Join(customers,
              x => x.CustomerId,
              y => y.CustomerId,
              (x, y) => new CustomerLookupResult()
              {
                CustomerId = y.CustomerId,
                Name = y.Name,
                IdentifierTypeCode = x.IdentifierTypeCode
              });

【讨论】:

    【解决方案2】:

    您也可以通过这种方式使用 Linq 来实现。

    var match = from t1 in context.orders
                        join t2 in context.orderdetails on
                               new { t1.OrderID } equals
                               new { t2.OrderID }
                        join t3 in context.products on
                               new { t2.ProductID } equals
                               new { t3.ProductID }
                        where t3.ProductID == id
                        select t3;
            return match.ToList();
    

    【讨论】:

      【解决方案3】:

      Join 的第一个参数采用任何 IEnumerable,因此您可以在此时或更早应用Where

      var q = query.Join(context.CustomerIds.Where(x=>x.IdentifierTypeCode=="LOYALTY"),
          x => x.CustomerId,
          y => y.CustomerId,
          (x, y) => new CustomerLookupResult()
          {
              dob = x.DateOfBirth.ToString(),
              forenames = x.Forenames,
              surname = x.Surname,
              loyaltyNo = y.Identifier,
             customerId = x.CustomerId
          });
      

      或者,如果您不喜欢在一行上放太多:

      var filteredLoyalties = context.CustomerIds.Where(x=>x.IdentifierTypeCode=="LOYALTY");
      var q = query.Join(filteredLoyalties,
          ...
      

      【讨论】:

        猜你喜欢
        • 2017-03-20
        • 2020-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        相关资源
        最近更新 更多