Reputation: 5877
Parent
-Child1
-GrandChild1
-GreatGrandChild1
-Name="Name One"
-GreatGrandChild2
-Name="Name Two"
-GreatGrandChild3
-Name="Name One"
-GrandChild2
-GreatGrandChild4
-Name="Name One"
-GreatGrandChild5
-Name="Name Three"
-GreatGrandChild6
-Name="Name One"
-GrandChild3
-GreatGrandChild7
-Name="Name One"
-GreatGrandChild8
-Name="Name Five"
-GreatGrandChild9
-Name="Name One"
-Child1
-GrandChild4
-GreatGrandChild10
-Name="Name One"
-GreatGrandChild11
-Name="Name Six"
-GreatGrandChild12
-Name="Name One"
-GrandChild5
-GreatGrandChild13
-Name="Name One"
-GreatGrandChild14
-Name="Name One"
-GreatGrandChild15
-Name="Name One"
-GrandChild6
-GreatGrandChild16
-Name="Name One"
-GreatGrandChild17
-Name="Name Seven"
-GreatGrandChild18
-Name="Name One"
I would like to select the Parent, Child, GrandChild and GreatGrandChild where GreatGrandChild's name is not Name One
.
How do I do that in Linq.
I tried with Select
, selectMany
along with Any
but it wasn't giving the desired result
Note: The collection is list of objects.
Upvotes: 1
Views: 1421
Reputation: 1
What you need to do is a deep copy with condition of the first list.
here is a little exemple:
var parentWithoutNameOne = new Parent
{
Childs = parent.Childs
.Select(o => new Child()
{
GrandChilds = o.GrandChilds.Select(p => new GrandChild
{
GreatGrandChilds = p.GreatGrandChilds
.Where(l => l.Name != "Name One")
.ToList()
}).ToList()
}).ToList()
};
And here are the definitions of the class i'm using:
public class Parent
{
public List<Child> Childs { get; set; }
}
public class Child
{
public List<GrandChild> GrandChilds { get; set; }
}
public class GrandChild
{
public List<GreatGrandChild> GreatGrandChilds { get; set; }
}
public class GreatGrandChild
{
public string Name { get; set; }
}
Upvotes: 0
Reputation: 3609
Since we need to manipulate the collection (to remove great grand children with "Name One"), LINQ alone won't be sufficient.
//assuming it is ok to mutate the existing list of Objects (parents)
var grandChildren = parents.SelectMany(p => p.Children).SelectMany(c => c.GrandChildren);
foreach (var grandChild in grandChildren)
{
grandChild.GreatGrandChildren.RemoveAll(x => x.Name == "Name One");
}
Upvotes: 1
Reputation: 6514
Does this doesnt work:
var hasAnyGreatGrandChildren = parent.Child.GrandChild
.SelectMany(x => x.GreatGrandChild)
.Any(x ==> x.Name != "Name One");
Upvotes: 0
Reputation: 3631
I think you're looking for something like this:
parent.ChildList = parent.ChildList.Where(x => x.GrandChildList.Any(y => y.Name == "Name One") == false).ToList();
Upvotes: 0