Linq查询根据不同的列值返回整行

时间:2017-08-03 15:25:53

标签: linq

我需要返回Customers中与ShipTo列不同的记录的所有列。我使用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()); 

2 个答案:

答案 0 :(得分:0)

咄!我需要添加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();

答案 1 :(得分:0)

如果我理解正确,您希望通过CustomerOrders分配任何订单的所有客户(每次一次)客户和订单#s ShipToOrderTypeOrderStatus上的其他一些约束相同(加上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();