嵌套列表 - 获取父列表的列表项

时间:2017-07-17 13:23:30

标签: c# list class nested parent-child

我想写一个C#函数,当我通过“Montgomery”时返回“alamaba”。

第二个例子:Sitka - >阿拉斯加

这是示例列表:

List<PopulationUSA> result = new List<PopulationUSA>();    

        PopulationUSA usa = new PopulationUSA("Population in USA", 316128839, new List<PopulationUSA>());
        result.Add(usa);

        PopulationUSA alabama = new PopulationUSA("Alabama", 4833722, new List<PopulationUSA>());
        usa.Items.Add(alabama);

            alabama.Items.Add(new PopulationUSA("Birmingham", 212113, null));
            alabama.Items.Add(new PopulationUSA("Montgomery", 201332, null));
            alabama.Items.Add(new PopulationUSA("Mobile", 194899, null));

        PopulationUSA alaska = new PopulationUSA("Alaska", 735132, new List<PopulationUSA>()); 
        usa.Items.Add(alaska);

            alaska.Items.Add(new PopulationUSA("Juneau", 32660, null));
            alaska.Items.Add(new PopulationUSA("Ketchikan", 8214, null));
            alaska.Items.Add(new PopulationUSA("Sitka", 9020, null));

这是班级:

    public class PopulationUSA
{
    public PopulationUSA(string name, int value, List<PopulationUSA> items)
    {
        Name = name;
        Value = value;
        Items = items; 
    }

    public string Name { get; set; }
    public int Value { get; set; }

    public List<PopulationUSA> Items { get; set; }
}

我该怎么做? 感谢

1 个答案:

答案 0 :(得分:0)

您可以将此方法添加到PopulationUSA类

  public string FindParentsOfGrandChildren(string _name)
    {
        List<PopulationUSA> parents = Items.Where(s => s.Items.Any(c => c.Name == _name)).ToList();
        if (parents != null)
        {
            string listparents = string.Empty;
            for (int i = 0; i < parents.Count; i++)
            {
                if (i == 0)
                {
                     listparents += parents[i].Name;
                }
                else
                {
                    listparents += ", " + parents[i].Name;
                }
            }
            return listparents;
        }
        else
        {
            return "Not found";
        }
    }

然后在你的例子中使用它:

 string WhereDoIBelong = usa.FindParentsOfGrandChildren("Montgomery")

作为递归方法会更好,找到任何类型的父母(不仅仅是“孙子”),但那是你的工作!