Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a nested collection using linq

Tags:

c#

linq

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.

like image 747
SJMan Avatar asked Jul 09 '15 05:07

SJMan


2 Answers

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 ;
like image 151
Mairaj Ahmad Avatar answered Sep 25 '22 11:09

Mairaj Ahmad


Here is an abridged lambda version for you:

persons.ForEach(p => p.CarsOwnedByHim.RemoveAll(c => c.ModelName == "Corolla"));
like image 21
Vaibhav Avatar answered Sep 26 '22 11:09

Vaibhav