2017-08-03 98 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();