2011-08-09 39 views
1

我有一個自定義項目的數組,然後我有一個由對象函數返回的對象數組[]。這個對象數組的確是相同的客戶端類型,但是它以對象類型數組的形式返回(我不能編輯這個方面)。從包含在自定義類數組中的對象[]移除項目

我試着用明確的轉換,但我在運行時得到一個異常說:無法將對象[]轉換爲客戶端[]。
我的目標是,一旦我有兩個陣列,將從一個列表中刪除另一個列表中存在的項目,並創建一個聯合以獲得唯一列表。

var client = getClients().ToArray();   //Is an array of Clients[] 
var normalSearch = getDuplicates().ToArray(); //Is an array of object[] 


//This what I try to achieve,but being object, I cannot invoke "c.ContactId" (Line 4) 
var uni = (from c in normalSearch 
      where !(from d in dupes 
        select d.ContactId) 
        .Contains(c.ContactId) 
      select c).ToArray(); 

我知道,在LINQ的聯盟()能自動排除重複的,如果使用基本類型,否則的擴展名必須與自定義類型來開發。但是我沒有訪問其餘的代碼,因此不可能在別處改變邏輯。

回答

1
getDuplicates().Cast<Client>(); 
+0

此演員表現正常! – Francesco

1
var uni = client.Union(normalSearch.Cast<Client>()) 
    .DistinctBy(c => c.ContractId); 

DistinctBy是在MoreLinq

如果您不能使用MoreLinq,你可以簡單地做

var uni = client.Union(normalSearch.Cast<Client>()) 
    .GroupBy(c => c.ContractId) 
    .Select(g => g.First()); 

這基本上是他們實現這一點。

+0

我得到DistinctBy一個例外,因爲我的IEnumerable集合沒有一個定義它。它是否在System.Linq以外的額外庫中,還是我必須編寫該擴展? – Francesco

+0

@Luca它在我鏈接到的MoreLinq庫中。 –

+0

+1謝謝,但我不能使用外部其他庫。 – Francesco

0

您可以使用linq將重複項轉換爲客戶端,然後創建一個比較器類。我複製並從msdn documentation粘貼此,可以根據需要進行調整

var normalSearch = getDuplicates().ToArray().Cast<Clients>(); 
var client = getClients().ToArray(); 

var unique = client.Union(normalSearch, new ClientsComparer()); 

public class ClientsComparer : IEqualityComparer<Clients> 
{ 
    public bool Equals(Clients x, Clients y) 
    { 

     //Check whether the compared objects reference the same data. 
     if (Object.ReferenceEquals(x, y)) return true; 

     //Check whether any of the compared objects is null. 
     if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 
      return false; 

     //Check whether the products' properties are equal. 
     return x.ContactId == y.ContactId; 
    } 

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects. 

    public int GetHashCode(Client client) 
    { 
     //Check whether the object is null 
     if (Object.ReferenceEquals(product, null)) return 0; 

     //Calculate the hash code for the product. 
     return client.ContactId.GetHashCode(); 
    } 

} 
+0

我知道這個解決方案,但是我不能在這個部分介紹新的代碼。 – Francesco

相關問題