I am trying filter class list inside parents class but need to return parents class.
C# Code:
// 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; }
}
How to return parents class after Linq filter the child class?(Just use Linq and return in one line and do not modify data or create a new class)
As List<T>
has a RemoveAll
method which modifies the list in place:
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.
: Create new object and assign parent properties. And assign filtered list for Children
.
return new Parents()
{
FatherName = Family.FatherName,
MotherName = Family.MotherName,
Children = Family.Children.Where(o => o.Name == "Peter")
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.