[英]Linq: Match to properties of child object in a list of child objects and return parent object from a list of parents
[英]Linq filter child class and return parents class?
我正在嘗試在父母 class 中過濾 class 列表,但需要返回父母 class。
C# 代碼:
// Must return `Parents` class
public Parents FilterByAge()
{
Parents Family = new Parents() { FatherName = "John", MotherName = "Mary" };
Family.Children = new List<Children>(){
new Children{ Name = "Peter",Age=20},
new Children{ Name = "Alber",Age=15},
new Children{ Name = "Alex",Age=10},
new Children{ Name = "Ched",Age=5},
};
// Fail here, It will return `Children` class instead of `Parents` class.
return Family.Children.Where(o => o.Name == "Peter");
// Fail too, will show 'Family does not contain a definition for Where'
//return Family.Where(f => f.Children.Any(c => c.Name == "Peter"));
}
class Parents
{
public string FatherName { get; set; }
public string MotherName { get; set; }
public List<Children> Children { get; set; }
}
class Children
{
public string Name { get; set; }
public int Age { get; set; }
}
如何在 Linq 過濾子 class 后返回父母 class?
由於List<T>
有一個RemoveAll
方法可以修改列表:
public Parents FilterByAge()
{
Parents family = new Parents() { FatherName = "John", MotherName = "Mary" };
family.Children = new List<Children>()
{
new Children{ Name = "Peter", Age = 20 },
new Children{ Name = "Alber", Age = 15 },
new Children{ Name = "Alex", Age = 10 },
new Children{ Name = "Ched", Age =5 }
};
family.Children.RemoveAll(child => child.Name != "Peter");
return family;
}
Just use Linq and return in one line.
:新建 object 並分配父屬性。 並為Children
分配過濾列表。
return new Parents()
{
FatherName = Family.FatherName,
MotherName = Family.MotherName,
Children = Family.Children.Where(o => o.Name == "Peter")
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.