2010-05-14 83 views
0

如何從c#中的另一個列表中刪除清單中的不同項目?刪除不同的項目

+1

什麼樣的名單呢?什麼樣的物品? – 2010-05-14 17:56:33

+1

哪個版本的.net平臺? – 2010-05-14 18:05:09

回答

2

你可以使用Except像這樣:

var result = list2.Except(list1).ToList(); 

因此,一個例子是:

List<int> a = new List<int>() { 1, 2, 3, 4, 5 }; 
List<int> b = new List<int>() { 1, 2, 3, 4 }; 
List<int> c = a.Except(b).ToList(); 

其中C組名單隻會在它的值5。

+0

感謝這就是我的意思 – kartal 2010-05-14 18:17:45

0
var distinctItems = items.Distinct(); 

不太你問什麼,但它是一個更容易通過複製要保留的項目,從一個新的列表,不是試圖編輯原始列表。

如果要控制列表項的「相等」的構成,請調用接受IEqualityComparer<T>實例的過載。

參見MSDN

1

不一樣優雅的使用除了(我從來不知道存在)...但這個工程:

List<string> listA = new List<string>(); 
    List<string> listB = new List<string>(); 

    listA.Add("A"); 
    listA.Add("B"); 
    listA.Add("C"); 
    listA.Add("D"); 

    listB.Add("B"); 
    listB.Add("D"); 

    for (int i = listA.Count - 1; i >= 0; --i) 
    { 
     int matchingIndex = listB.LastIndexOf(listA[i]); 

     if (matchingIndex != -1) 
      listB.RemoveAt(matchingIndex); 
    } 
+0

好吧,我測試了Except方法,它絕對更優雅: List listC = listA.Except(listB).ToList(); 這將創建第三個列表,其中只有listA中的項目不在listB中。 – beaudetious 2010-05-14 18:13:34

+0

希望他們會允許在評論中格式化! :) – beaudetious 2010-05-14 18:13:56