简体   繁体   English

如何从列表中删除在同一列表中有父母的项目

[英]How to remove from the list the items that have parents in the same list

I have a List<Item> . 我有一个List<Item>

How can I remove items that have parents in the same list using LINQ? 如何使用LINQ删除父母在同一列表中的项目?

If it is possible I prefer method chain expression. 如果可能的话,我更喜欢方法链表达式。

Item definition: 项目定义:

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

This may help 这可能会有所帮助

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
var Children = List.Where(child => List.Any(parent => parent.Id == child.ParentID)).ToList();
List.RemoveAll(child => Children.Contains(child));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM