我有两个类 Parent 和 Child。我想要获取所有孩子符合某些条件的父母,例如所有父母和他们的女儿。我想使用 Linq
进行此操作。我已经使用以下 Linq
查询,并返回所有有女儿的父母,但 children 列表中也包括男孩子。我只想在 List<Parent> parentsAndFemaleChildren
中包含父母和他们的女儿,请参见下面的 Linq
查询:
请帮我修改这个查询来获得我所需的结果。
List<Parent> parentsAndFemaleChildren = Parents
.Where(p => p.Children.Any((c => c.Gender == "Female")))
.ToList();
以下是填充数据的代码。
public class Parent
{
public int ParentId {get;set;}
public string ParentName {get;set;}
public List<Child> Children {get;set;}
}
public class Child
{
public int ChildId {get;set;}
public string ChildName {get;set;}
public string Gender {get;set;}
public int ParentId {get;set;}
}
我已按如下方式填充数据。
public static void Main()
{
List<Parent> Parents = new List<Parent>();
Parent p1 = new Parent();
p1.ParentId = 1;
p1.ParentName = "Parent 1";
Parents.Add(p1);
Child p1C1 = new Child();
p1C1.ChildId = 1;
p1C1.ChildName = "Parent 1 Child 1";
p1C1.Gender = "Male";
p1C1.ParentId = 1;
p1.Children = new List<Child>();
p1.Children.Add(p1C1);
Child p1C2 = new Child();
p1C2.ChildId = 2;
p1C2.ChildName = "Parent 1 Child 2";
p1C2.Gender = "Female";
p1C2.ParentId = 1;
p1.Children.Add(p1C2);
Parent p2 = new Parent();
p2.ParentId = 2;
p2.ParentName = "Parent 2";
Parents.Add(p2);
Child p2C1 = new Child();
p2C1.ChildId = 3;
p2C1.ChildName = "Parent 2 Child 1";
p2C1.Gender = "Female";
p2C1.ParentId = 2;
p2.Children = new List<Child>();
p2.Children.Add(p2C1);
Child p2C2 = new Child();
p2C2.ChildId = 4;
p2C2.ChildName = "Parent 2 Child 2";
p2C2.Gender = "Male";
p2C2.ParentId = 2;
p2.Children.Add(p2C2);
Parent p3 = new Parent();
p3.ParentId = 3;
p3.ParentName = "Parent 3";
Parents.Add(p3);
Child p3C1 = new Child();
p3C1.ChildId = 5;
p3C1.ChildName = "Parent 3 Child 1";
p3C1.Gender = "Male";
p3C1.ParentId = 3;
p3.Children = new List<Child>();
p3.Children.Add(p3C1);
DisplayFemaleChildrenAndParents(Parents);
}
public static void DisplayFemaleChildrenAndParents(List<Parent> Parents)
{
List<Parent> parentsAndFemaleChildren = Parents.Where(p => p.Children.Any((c => c.Gender == "Female"))).ToList();
Console.WriteLine("\nShould Display Parents and their Female children details ONLY\n");
foreach(Parent p in parentsAndFemaleChildren)
{
Console.WriteLine("***********");
foreach(Child c in p.Children)
{
Console.WriteLine(p.ParentName + " - " + c.ChildName + " - " + c.Gender);
}
Console.WriteLine("***********");
}
}
完整代码可以通过 dotnet fiddle 查看和运行,点击这里。