从嵌套列表中检索数据

Retrieve data from the nested list

提问人:Milad Ahmadi 提问时间:1/14/2023 最后编辑:Yong ShunMilad Ahmadi 更新时间:1/14/2023 访问量:59

问:

如何从 C# 中的嵌套列表中获取所有数据?

每个人可以拥有多辆车。

现在我有一个人员列表,每个项目都有一个汽车列表。

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

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

和价值观:

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"
            }
        }
    }
};

通过一个查询获取所有汽车名称的最佳方法是什么?

是否可以通过一个查询获得所有汽车?

C# 列表 嵌套列表

评论


答:

3赞 Yong Shun 1/14/2023 #1

使用 System.Linq,可以使用列表中的列表展平并获取 ..SelectMany()CarspeopleName

using System.Linq;

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

演示 @ .NET Fiddle