2013-05-05 67 views
0
public struct RegistryApp 
{ 
    public string VendorName; 
    public string Name; 
    public string Version; 
} 

的Structs的列表中刪除的項目,我有兩個List<RegistryApp>持有目前安裝在Windows中所有應用程序。爲什麼兩個?那麼我有一個列表來保存所有x86應用程序,一個用於保存所有x64應用程序。如何從存在於其他目錄

List<RegistryApp> x64Apps64List = new List<RegistryApp>(); 
List<RegistryApp> x64Apps32List = new List<RegistryApp>(); 

一旦這兩個都填充了其從註冊表中檢索到自己合適的數據,我嘗試以下方法,以確保有沒有重複。這在List<string>上正常工作,但不適用於List<RegistryApp>

List<RegistryApp> ListOfAllAppsInstalled = new List<RegistryApp>(); 

IEnumerable<RegistryApp> x86Apps = x64Apps32List.Except(x64Apps64List); 
IEnumerable<RegistryApp> x64Apps = x64Apps64List.Except(x64Apps32List); 

foreach (RegistryApp regitem in x86Apps) 
{ 
    if ((regitem.Name != null) && 
    (regitem.Name.Length > 2) && 
    (regitem.Name != "")) 
    { 
     ListOfAllAppsInstalled.Add(regitem); 
    } 
} 

foreach (RegistryApp regitem in x64Apps) 
{ 
    if ((regitem.Name != null) && 
    (regitem.Name.Length > 2) && 
    (regitem.Name != "")) 
    { 
     ListOfAllAppsInstalled.Add(regitem); 
    } 
} 

有什麼辦法可以解決這個問題嗎?

回答

5

EDITED

要存在於另一個表中,可以看到Cuong Le這裏提供的解決方案的Structs的列表中刪除項目:

https://stackoverflow.com/a/12784937/1507182

通過使用List類型的Distinct無參數擴展方法,我們可以刪除那些重複的元素。

然後,我們可以選擇調用ToList擴展來獲取刪除重複項的實際列表。

static void Main() 
    { 
    // List with duplicate elements. 
    List<int> mylist = new List<int>(); 
    mylist.Add(1); 
    mylist.Add(2); 
    mylist.Add(3); 
    mylist.Add(3); 
    mylist.Add(4); 
    mylist.Add(4); 
    mylist.Add(4); 

    foreach (int value in mylist) 
    { 
     Console.WriteLine("Before: {0}", value); 
    } 

    // Get distinct elements and convert into a list again. 
    List<int> distinct = mylist.Distinct().ToList(); 

    foreach (int value in distinct) 
    { 
     Console.WriteLine("After: {0}", value); 
    } 
    } 

如果我的回答已經解決了您的問題,點擊接受的解決方案按鈕,這樣做會幫助別人知道解決的辦法。

2

對於Execpt工作你正在使用它的東西必須是可比較的。爲了使您的自定義工作結構,你需要做兩件事情之一,無論是覆蓋GetHashCodeEquals能夠使用Execpt與結構:

public struct RegistryApp 
{ 
    public string VendorName; 
    public string Name; 
    public string Version; 

    public override bool Equals(object obj) 
    { 
     if (!(obj is MyStruct)) 
      return false; 

     RegistryApp ra = (RegistryApp) obj; 

     return ra.VendorName == this.VendorName && 
       ra.Name == this.Name && 
       ra.Version == this.Version; 

    } 

    public override int GetHashCode() 
    { 
     return VendorName.GetHashCode()^Name.GetHashCode()^Version.GetHashCode(); 
    } 

} 

或使用overload of Execpt,使您可以通過在你自己的比較器,並通過它。See the MSDN for an example

+0

我明白了爲什麼我現在得到-1,我已經修復了措辭。 – 2013-05-05 01:28:19

+0

這看起來像它會工作,但我無法得到它的工作,我測試了Obamas代碼,它的工作,我不得不做一些改變:'List UniqueEntries = ListOfAllAppsInstalled.Distinct()。ToList (); ' – Dayan 2013-05-05 02:16:17