C# Linq-删除嵌套集合中的对象
我想选择父、子、孙和曾孙,其中曾孙的名字不是C# Linq-删除嵌套集合中的对象,c#,linq,C#,Linq,我想选择父、子、孙和曾孙,其中曾孙的名字不是name One 在林克我该怎么做 我尝试了Select,selectMany以及Any,但没有得到预期的结果 注意:该集合是对象列表。我想您正在寻找类似的内容: Parent -Child1 -GrandChild1 -GreatGrandChild1 -Name="Name One" -GreatGrandChild2
name One
在林克我该怎么做
我尝试了Select
,selectMany
以及Any
,但没有得到预期的结果
注意:该集合是对象列表。我想您正在寻找类似的内容:
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"
这不管用吗:
parent.ChildList = parent.ChildList.Where(x => x.GrandChildList.Any(y => y.Name == "Name One") == false).ToList();
因为我们需要操纵集合(用“名字一”删除伟大的孙子孙女),光靠LINQ是不够的
var hasAnyGreatGrandChildren = parent.Child.GrandChild
.SelectMany(x => x.GreatGrandChild)
.Any(x ==> x.Name != "Name One");
您需要做的是一个具有第一个列表条件的深度副本 这里有一个小例子:
//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");
}
下面是我使用的类的定义:
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()
};
公共类父类
{
公共列表子项{get;set;}
}
公营儿童
{
公共列表孙子{get;set;}
}
公家子弟
{
公共列表曾孙{get;set;}
}
公共级曾孙
{
公共字符串名称{get;set;}
}
Linq用于查询数据,而不是删除或操作数据。收藏的实际类型是什么?这是Linq到实体还是Linq到对象还是另一个Linq后端?@Dai这只是嵌套对象的列表。请发布对象的定义-不清楚这是相同对象类的通用树还是父对象、子对象,和grant
是独立的类型。您能编辑帖子并为给出的示例数据添加预期的输出数据吗?同意@Dai,在不知道对象结构的情况下,无法向您显示正确的投影。
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; }
}