【问题标题】:Nested List — Get list item of parent list嵌套列表 - 获取父列表的列表项
【发布时间】:2017-07-17 13:23:30
【问题描述】:

我想编写一个 C# 函数,当我通过“蒙哥马利”时返回“alamaba”。

第二个例子:锡特卡 --> 阿拉斯加

这里是示例列表:

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

我该怎么做? 谢谢

【问题讨论】:

  • 真的不清楚你在问什么或者你的问题出在哪里。此外,最好展示一个您迄今为止尝试过的示例
  • 我会建议重组你的班级。一个定义了相同类列表的类并不能很好地说明如何使用它。
  • @BlakeThingstad 所以应该重新设计 TreeViewItem?
  • @RomanoZumbé - 我认为正确使用是有意义的。使用TreeView 结构,它绝对是有意义的,但它有助于名称描述它的用途(以及 Item 用于 TreeView)。至少非常,OP 可以使类的名称比“PopulationUSA”更具描述性。
  • @RomanoZumbé 我不会这么说,因为它的名称表明了结构的使用。我只是说,如果 OP 没有发布显示代码的代码,我们不会知道 OP 在顶层使用 PopulationUSA 来代表美国,第二层是美国,底层是城市。

标签: c# list class nested parent-child


【解决方案1】:

您可以将此方法添加到 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")

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

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    相关资源
    最近更新 更多