Search code examples
c#listlinq

Filter nest data by Linq (C#, Linq)


I have objects:

public class Cars
{
 public id CarId {get;set;}
 public ClientList[] AvaList {get;set;}
}

public class ClientList
{
 Client[] ClientData {get;set;}
}

public class Client
{
 int ClientId {get;set;}
}

In method Im geting list of Cars:

string cId = 10;
IEnumerable<Cars> cars = GetCars();
var carsForClientId = cars.AvaList.SelectMany(c => c.ClientData.Where(x => x.ClientId == cId));

But carsForClientId is IEnumerable<Client>. And I want to get IEnumerable<Cars> contains only data for CliendId = 10;


Solution

  • You have to select cars:

    var carsForClientId = cars
        .Where(c => c.AvaList
            .Any(clist => clist.ClientData
                .Any(cl => cl.ClientId == cId)));