简体   繁体   English

通过检查列表C#的父ID,从列表中删除具有Chilid项目的父项目。

[英]Remove parent items from a list when having chilid items by checking parent IDs of the list c#

I have a list which has both parent and child service items. 我有一个包含父母和子女服务项目的列表。 I need to get all the parent services which does not have any child service and all the child services into one list. 我需要将没有任何子服务的所有父服务和所有子服务合并到一个列表中。 That means I want to remove the items which has child items. 这意味着我要删除具有子项的项。 How can I do this using LINQ? 如何使用LINQ做到这一点? My list is something like below 我的清单如下

public class Service
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public int Parent { get; set; }
 }

 var ServiceList = new List<Service>();
 ServiceList.Add(new Service() { Id = 1, Name = "service 1", Parent= -1 });
 ServiceList.Add(new Service() { Id = 2, Name = "service 2", Parent= -1 });
 ServiceList.Add(new Service() { Id = 3, Name = "service 3", Parent= -1 });
 ServiceList.Add(new Service() { Id = 4, Name = "Service 4", Parent= 2 });
 ServiceList.Add(new Service() { Id = 5, Name = "Service 5", Parent = 2 });
 ServiceList.Add(new Service() { Id = 6, Name = "Service 6", Parent = -1 })

With the above list I want to remove "Service 2" from the list. 使用上面的列表,我想从列表中删除“服务2”。 Since there are two child services for that parent service. 由于该父服务有两个子服务。 I want to keep all other parent and child services in the list. 我想将所有其他父级和子级服务保留在列表中。

You need to filter every service, Where the Id of the service is Not the parent id of Any other service in the collection. 您需要过滤每个服务,其中服务的ID不是集合中任何其他服务的父ID。

var result = ServiceList
    .Where(parent => !ServiceList.Any(child => parent.Id == child.Parent));

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

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