I have two classes, one nested within the other,
class Person
{
public string Name;
public string SSN;
public List<Car> CarsOwnedByHim;
}
and another class car
class Car
{
public string RegNo;
public string Make;
public string ModelName;
}
from a List<Person>
I would like to filter out all the cars of , say ModelName = "Corolla".
Note that the person instance should be returned, but in the nested list only the cars should be filtered out.
The below solution is working, but I am looking for a more elegant soution.
List<Person> lstPersons = new List<Person>();
foreach (var person in _result)
{
List<Car> lstCars = new List<Car>();
foreach (var car in person)
{
if (car.ModelName != "Corolla")
lstCars.Add(car);
}
var tempPerson = person;
tempPerson.CarsOwnedByHim = lstCars;
lstPersons.Add(tempPerson);
}
return lstPersons ;
This is just a modified version of the original problem.TIA.
Try this. You can get list
of cars of a person where make is not equal
to corolla by using Where
clause like this
lstCars = person.CarsOwnedByHim.Where(x => x.ModelName.ToUpper() != "COROLLA").ToList();
Yor whole code would be like this
List<Person> lstPersons = new List<Person>();
foreach (var person in _result)
{
List<Car> lstCars = new List<Car>();
lstCars=person.CarsOwnedByHim.Where(x => x.ModelName.ToUpper() != "COROLLA").ToList();
person.CarsOwnedByHim = lstCars;
lstPersons.Add(person);
}
return lstPersons ;
Here is an abridged lambda version for you:
persons.ForEach(p => p.CarsOwnedByHim.RemoveAll(c => c.ModelName == "Corolla"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With