Home > Software engineering >  Read data from nested list
Read data from nested list

Time:01-14

How can I get all data from nested list in C#
Each person can have multiple cars.
Now I have a list from people and each item in this list have 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 that 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

  •  Tags:  
  • c#
  • Related