希望从两个不同层次的嵌套列表中获取信息

Looking to get information from two different tiers of nested lists

我正在尝试使用 LINQ 使用 2 个 foreach 循环来简化查询。

我有以下代码:

// Create a dictionary of all the pets where the key is building # + owner name + pet's age
Dictionary<string, Pet> petDictionary = new Dictionary<string, Pet>();
        foreach (Tenant tenant in allTenants){
            foreach (Pet pet in tenant.PetList){
                petDictionary.Add(tenant.BuildingNumber  + "-" + tenant.Name + "-" + pet.Age, pet);
            }
        }
        foreach (KeyValuePair<string, Pet> petKvp in petDictionary){
            Console.WriteLine("Name: {0,20} | secret Id: {1}", petKvp.Value.Name, petKvp.Key);  
        }

代码有效,但我想使用 ToDictionary 替换上面的嵌套 foreach 循环。有人可以告诉我如何使用 LINQ 执行此操作吗?

我已经尝试了几件事,但我无法找到如何在同一个 LINQ 查询中从租户列表和宠物列表中获取信息。

租户Class:

public class Tenant
{
    // Attributes
    public string Name{ get; set;}
    public int BuildingNumber{ get; set;}
    public List<Pet> PetList{get; set;}
}

宠物Class:

public class Pet
{
    // Attributes
    public string Name{ get; set;}
    public int Age{ get; set;}
}

您可以使用 LINQ 执行此操作并生成新词典,而无需事先声明您的词典并向其中添加项目。

public void CombineTenatsAndPets()
{
    //Create data
    var tenants = Enumerable.Range(0, 10).Select(_ => new Tenant()
    {
        PetList = Enumerable.Range(0, 5).Select(_ => new Pet()).ToList()
    });

    var tenantsAndPets = tenants
        .SelectMany(t =>
            t.PetList.Select(p => new KeyValuePair<string, Pet>(
                    $"{t.BuildingNumber}-{t.Name}-{p.Age}", p)))
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}