2013-03-28 77 views
1

我有一個List<Item>如何從列表中刪除父母在同一個列表中的項目

如何刪除使用LINQ在同一列表中有父母的項目?

如果可能我更喜歡方法鏈表達式。

產品定義:

public class Item { 
     public int Id { get; set; } 
     public int ParentId { get; set; } 
    } 
+0

你的意思是除去具有相同的'ParentId'項目? – Rob 2013-03-28 11:26:57

+3

所有使用「RemoveAll」的人都會失敗。您必須構建相關項目的新列表,然後替換列表。因爲在檢查「b」是否應該刪除之前,您可能會刪除它是「b」項的父項的項目「a」。 – 2013-03-28 11:41:02

+0

@RoeeGavirel感謝您指出RemoveAll可能會失敗的樹木。 – 2013-03-28 12:01:57

回答

3
var Children = List.Where(child => List.Any(parent => parent.Id == child.ParentID)).ToList(); 
List.RemoveAll(child => Children.Contains(child)); 
+0

現在,工作(:[-1 ==> +1] – 2013-03-28 12:03:03

+2

@RoeeGavirel這將教會我不要發佈未經測試的代碼! – 2013-03-28 12:08:41

3

這可能有助於

List<Item> items = new List<Item>(); 
items.Add(new Item() { Id = 1, ParentId = 2 }); 
items.Add(new Item() { Id = 2, ParentId = 0 }); 
items.Add(new Item() { Id = 3, ParentId = 0 }); 
items.Add(new Item() { Id = 4, ParentId = 1 }); 
items.Add(new Item() { Id = 5, ParentId = 1 }); 
items.Add(new Item() { Id = 6, ParentId = 4 }); 
items.Add(new Item() { Id = 7, ParentId = 4 }); 
items.Add(new Item() { Id = 8, ParentId = 4 }); 
items.Add(new Item() { Id = 9, ParentId = 4 }); 
items.Add(new Item() { Id = 10, ParentId = 4 }); 
items.Add(new Item() { Id = 11, ParentId = 4 }); 

var shouldBeRemove = 
    (from i in items 
    where items.Any(input => input.Id == i.ParentId) 
    select i).ToList(); 

items.RemoveAll(input => shouldBeRemove.Contains(input)); 

//Those who remain 
//item with Id = 2 
//item with Id = 3 
+1

失敗。如果對於Id-6,父母是4,則不會被移除,因爲在檢查之前Id-4將被移除。 – 2013-03-28 11:39:19

+0

@RoeeGavirel你有沒有試過你的想法?我測試它,它有效 – 2013-03-28 11:41:08

+0

我做到了,看到你改變了你的答案你也做了( - : - >我把(-1)改成了(+1) – 2013-03-28 12:02:01