user2837480
user2837480

Reputation: 369

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? 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. Since there are two child services for that parent service. I want to keep all other parent and child services in the list.

Upvotes: 1

Views: 341

Answers (1)

Stucky
Stucky

Reputation: 156

You need to filter every service, Where the Id of the service is Not the parent id of Any other service in the collection.

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

Upvotes: 2

Related Questions