Home > database >  Retrieve data from the nested list
Retrieve data from the nested list

Time:01-14

How can I get all data from a nested list in C#?

Each person can have multiple cars.

Now I have a list of people and each item has a list of cars.

public class Person
{
    public string FullName { get; set; }
    public List<Car> Cars { get; set; }
}

public class Car
{
    public string Name { get; set; }
}

And values:

var people = new List<Person>()
{
    new Person()
    {
        FullName = "Jack Lee",
        Cars = new List<Car>()
        {
            new Car()
            {
                Name = "BMW"
            },
            new Car()
            {
                Name = "Tesla"
            }
        }
    },
    new Person
    {
        FullName = "Micheal doug",
        Cars = new List<Car>()
        {
            new Car()
            {
                Name = "Ferrari"
            }
        }
    }
};

What is the best way to get all car names with one query?

Is it possible to get all cars with one query?

CodePudding user response:

With System.Linq, you can use .SelectMany() to flatten the Cars lists from the people list and get the Name.

using System.Linq;

var result = people.SelectMany(x => x.Cars)
    .Select(x => x.Name)
    .ToList();

Demo @ .NET Fiddle

  • Related