如何从列表中删除同一列表中包含父项的项目

时间:2013-03-28 11:25:31

标签: c# linq

我有List<Item>

如何使用LINQ删除同一列表中包含父项的项目?

如果有可能,我更喜欢方法链表达。

项目定义:

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

2 个答案:

答案 0 :(得分: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 :(得分:3)

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