如何從c#中的另一個列表中刪除清單中的不同項目?刪除不同的項目
刪除不同的項目
回答
你可以使用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。
感謝這就是我的意思 – kartal 2010-05-14 18:17:45
var distinctItems = items.Distinct();
不太你問什麼,但它是一個更容易通過複製要保留的項目,從一個新的列表,不是試圖編輯原始列表。
如果要控制列表項的「相等」的構成,請調用接受IEqualityComparer<T>
實例的過載。
參見MSDN。
不一樣優雅的使用除了(我從來不知道存在)...但這個工程:
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);
}
好吧,我測試了Except方法,它絕對更優雅: List
希望他們會允許在評論中格式化! :) – beaudetious 2010-05-14 18:13:56
- 1. 自刪除清單不刪除項目
- 2. 刪除,項目不能刪除文件
- 3. Powershell刪除項目不會刪除所有項目
- 4. 刪除項目不還
- 5. 不BlockingCollection.GetConsumingEnumerable()刪除項目
- 6. 刪除的項目
- 7. 刪除項目
- 8. 刪除項目
- 9. 刪除項目
- 10. 刪除項目
- 11. jQuery同位素項目刪除
- 12. 刪除-項目Vs的[有System.IO.File] ::刪除()
- 13. 如何刪除項目刪除時的「,」?
- 14. 灰燼jQuery UI的排序刪除不同步的項目
- 15. 刪除類項目
- 16. SQLite刪除項目
- 17. 刪除Android項目
- 18. RecyclerView項目刪除
- 19. 刪除recyclerview項目
- 20. Gridview刪除項目
- 21. Spinner刪除項目
- 22. 刪除項目angularjs
- 23. 刪除項目7
- 24. 移除/刪除laravel項目
- 25. RCP exportWizard刪除不必要的項目
- 26. 不刪除Arraylist中的特定項目
- 27. 刪除不同標籤中的列表項目
- 28. 從不同的線程之謎中刪除ObservableCollection項目
- 29. 而不刪除項目不止一次
- 30. ListView項目的刪除選項總是刪除第一個項目,而不管哪個項目被點擊
什麼樣的名單呢?什麼樣的物品? – 2010-05-14 17:56:33
哪個版本的.net平臺? – 2010-05-14 18:05:09