【问题标题】:Linq query that returns entire rows based on a distinct column value基于不同列值返回整行的 Linq 查询
【发布时间】:2017-08-04 16:49:11
【问题描述】:

我需要返回与ShipTo 不同的Customers 记录的所有列。我使用Distinct() 尝试了此查询,但它返回重复记录:

var query = (from o in Orders
             from c in Customers
             where (from x in CustomerOrders
                    where x.CustomerId == customerId
                    && !x.OrderType.Equals('A')
                    select x.OrderId).Contains(o.OrderId)
             && c.CustomerId == customerId
             && c.ShipTo == o.ShipTo
             && !o.OrderStatus.Equals('C')
             select c).Distinct();

然后我尝试使用Group ByFirst() 重写查询。我没有收到任何语法错误,但是在使用 LinqPad 进行测试时查询会引发异常。

var query = (from o in Orders
             from c in Customers
             where (from x in CustomerOrders
                    where x.CustomerId == customerId
                    && !x.OrderType.Equals('A')
                    select x.OrderId).Contains(o.OrderId)
             && c.CustomerId == customerId
             && c.ShipTo == o.ShipTo
             && !o.OrderStatus.Equals('C')
             group c by c.ShipTo into g
             select g.First()); 

【问题讨论】:

  • Customer 的所有列但与 ShipTo 不同”听起来很矛盾。

标签: linq


【解决方案1】:

呃!我需要添加orderby c.ShipTo。它现在可以根据需要为我工作。

var query = (from o in Orders
             from c in Customers
             where (from x in CustomerOrders
                    where x.CustomerId == customerId
                    && !x.OrderType.Equals('A')
                    select x.OrderId).Contains(o.OrderId)
             && c.CustomerId == customerId
             && c.ShipTo == o.ShipTo
             && !o.OrderStatus.Equals('C')
             orderby c.ShipTo
             select c).Distinct();

【讨论】:

  • 这仍然不会在ShipTo 列上执行Distinct()
【解决方案2】:

如果我理解正确,您希望通过CustomerOrders 分配任何 订单的所有客户(每个客户一次),其中客户和订单的ShipTo 相同,外加一些其他限制在OrderTypeOrderStatus 上(加上customerId 上的过滤器,这似乎将结果集限制为最多一个)。

结果如下:

var qCustomer =
    from c in Customers
    where c.CustomerId == customerId && 
    (
        from co in CustomerOrders where co.CustomerId == c.CustomerId && co.OrderType != 'A'
        join o in Orders on co.OrderType equals o.OrderId where o.OrderStatus != 'C' && o.ShipTo == c.ShipTo
        select 1
    ).Any()
    select c;

或等效

var qCustomer =
    (
    from c in Customers
    join co in CustomerOrders on c.CustomerId equals co.CustomerId
    join o in Orders on co.OrderId equals o.OrderId
    where c.CustomerId == customerId && co.OrderType != 'A' && o.OrderStatus != 'C' && c.ShipTo == o.ShipTo
    select c
    ).Distinct();

由于该 ID 最多有一个客户:

var customerOrNull = qCustomer.SingleOrDefault();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多