2015-11-27 46 views
2

我有一個任務,我必須加入兩個相同類型的列表(Customer)。他們有類似的條目,我必須避免重複。使用linq查詢加入兩個列表 - C#

這是我客戶類:

class Customer 
{ 
    private String _fName, _lName; 
    private int _age, _cusIndex; 
    private float _expenses; 

    public Customer(String fName, String lName, int age, float expenses, int cusIndex) 
    { 
    this._fName = fName; 
    this._lName = lName; 
    this._age = age; 
    this._expenses = expenses; 
    this._cusIndex = cusIndex; 
    } 
} 

所以我有一個名爲customers1和秒。我需要加入這兩個不使用集合方法(如customer1.Union(customer2).ToList();但使用LINQ查詢

這裏的Linq查詢我寫道:

var joined = (from c1 in customers1 
       join c2 in customers2 
       on c1.CusIndex equals c2.CusIndex 
       select new {c1, c2}); 

但是這給了我是誰出現在雙方的成員但是我需要所有,沒有重複,有沒有解決方案?

+0

1.覆蓋[Equals](https://msdn.microsoft.com/library/ms173147.aspx)和[GetHashCode](http://blogs.msdn.com/b/ericlippert/archive/2011/02 /28/guidelines-and-rules-for-gethashcode.aspx)在你的Customer類中(以反映兩個客戶被認爲是平等的,如果他們的'CusIndex'相等的話)。 2.'var joined = customers1.Concat(customers2).Distinct();' – Corak

+1

它看起來好像沒有'Union'方法的查詢等價物。不使用'Union'方法的原因是什麼? –

+0

@Corak是的。我已經做到了。但問題是,此查詢返回兩個列表中的客戶。但我需要每個人 –

回答

7

看起來好像沒有對於Union方法的查詢等價物,您將需要在方法鏈調用或查詢中使用此方法。

如果你看一下MSDN documentation在返回兩個序列的並集,你會看到下面的官方查詢:

var infoQuery = 
    (from cust in db.Customers 
    select cust.Country) 
    .Union 
     (from emp in db.Employees 
     select emp.Country) 
; 

所以,只有兩個在您的情況選擇:

  1. 方法鏈:

    var joined = customers1.Union(customers2); 
    
  2. LINQ查詢

    var joined = (from c1 in customers1 
           select c1) 
          .Union 
           (from c2 in customers2 
            select c2); 
    
1

爲什麼不使用Distinct濾除重複?

var joined = (from c1 in customers1 
      join c2 in customers2 
      on c1.CusIndex equals c2.CusIndex 
      select new {c1, c2}).Distinct(); 

有在Microsoft.Ajax.Utilities一個很好的extension。它有一個叫做DistinctBy的功能,它可能與你的情況更相關。

+0

我用過這個。但是當我試圖用'ToList()'方法將它轉換成新的List時,它給了我Error。 '不能隱式轉換類型' –

+0

這與[self join](http://www.tutorialspoint.com/sql/sql-self-joins.htm)類似。 ToList()會給你一個匿名集合。我很困惑你想要達到的目標。您不能將匿名類型轉換爲已知類型。 –

+0

正如我所提到的,我需要加入兩個沒有重複元素的列表。這是作業的一部分! –