【发布时间】:2020-05-07 13:19:09
【问题描述】:
我有两个类,父类和子类。我想让所有孩子符合某些标准的父母,例如所有父母及其女孩。我想使用Linq 来做到这一点。我使用了以下Linq 查询,它返回所有有女孩的父母,但是孩子列表也包含男孩。我只想在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 click here 查看和运行完整代码。
【问题讨论】:
-
我喜欢带有可行样本的问题。