2014-01-27 105 views
0

我做左連接和右連接,然後進行全外辦聯合聯接這裏是我的代碼全外連接的Linq

var brndT = (from a in db.TSA_TARGET_DETAIL 
         where a.OUTLET_ID == id && a.CAMPAIGN_ID == campaignId && a.EMPLOYEE_ID == empId 
         select new 
         { 
          ID=a.BRAND_ID, 
          Target=a.STICK_QTY 
         }).ToList(); 

      var brndS = (from p in db.SR_TRN_DETAILS 
         where 
          (from ppt in db.SR_TRN_MAIN 
          where 
          ppt.MEMO_DATE >= d2 && ppt.MEMO_DATE <= d1 && ppt.OUTLET_ID==id 
          select ppt.ORDER_ID).Contains(p.ORDER_ID) 
         group p by p.BRAND_ID into g 
         select new 
         { 
          ID = g.Key, 
          Qty = g.Select(x => x.QUANTITY).Sum() 
         }).ToList(); 
      var left = (from T in brndT 
         join S in brndS 
         on T.ID equals S.ID 
         into temp 
         from S in temp.DefaultIfEmpty() 
         select new BrandSalesTarget 
         { 
          ID=T.ID, 
          Target = T.Target==null?0:(int)T.Target, 
          Sales = S != null ? (int)S.Qty : 0, 
         }).ToList(); 
      var right = (from S in brndS 
         join T in brndT 
         on S.ID equals T.ID 
         into temp 
         from T in temp.DefaultIfEmpty() 
         select new BrandSalesTarget 
         { 
          ID=S.ID, 
          Sales = S.Qty==null?0:(int)S.Qty, 
          Target = T != null ? (int)T.Target : 0 
         }).ToList(); 
      var fullOuter = left.Union(right).ToList(); 

但工會不起作用。我得到了兩次相同的ID。我的代碼有什麼問題?任何人的幫助,不勝感激。提前致謝。

+0

所有的事情似乎都沒問題,如果你從最後一行刪除'.ToList'就像這樣:'var fullOuter = left.Union(right);' – Hamidreza

+0

我沒有時間調查,但我的一個最初的猜測是班級'BrandSalesTarget'不知道如何比較自己。或者你需要一個比較器,如下所示:http://stackoverflow.com/questions/5969505/using-iequalitycomparer-for-union – TTT

回答

0

嘗試使用IEqualityComparer,以便聯合知道哪些元素相同。

借用的代碼。 union in two linq statements and remove the duplicate

class FirstElementComparer : IEqualityComparer<string[]> 
{ 
    //TODO error checking 
    public bool Equals(string[] a, string[] b) 
    {  
     return a[0].Equals(b[0]); 
    } 

    public Int32 GetHashCode(string[] obj) 
    { 
     return obj[0].GetHashCode(); 
    } 
} 

,並使用它像這樣:

void Main() 
{ 
    string[][] query1 = {new [] {"this is a test","Yes", "This is a remark"}, 
         new [] {"this is a test2","No", "This is the second remark"}}; 

    string[][] query2 = {new [] {"this is a test","",""}, 
         new [] {"this is a test2","",""}, 
         new [] {"this is a test3","",""}, 
         new [] {"this is a test4","",""}}; 

    query1.Union(query2, new FirstElementComparer()).Dump();       
} 

的EqualityComparer用於通過聯盟在QUERY1的元素,其QUERY2的元素進行比較。它通過比較每個數組中的第一項來實現。

我將來請簡化您的代碼以顯示實際問題的最少行數,理想情況下可以運行一個完整的簡短程序的形式,可以運行而不是複製和粘貼任何助手將會擁有的大量生產代碼用來重現問題的麻煩。