2017-08-03 107 views
0

我需要返回Customers中与列ShipTo不同的记录的所有列。我试着用Distinct()此查询,但它返回重复记录:Linq查询返回基于不同列值的整个行

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()); 
+0

“全部'Customer'列但通过“ShipTo”截然不同“听起来像是一个矛盾。 – tinudu

回答

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(); 
+0

这仍然不会对'ShipTo'列做一个'Distinct()'。 – NetMage

0

如果我理解正确的话,你希望所有的客户(各一次)已经通过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();