从c#的字符串构建层次结构

本文关键字:构建 层次结构 字符串 | 更新日期: 2023-09-27 18:03:59

我有一个字符串集合:

"Alberton;Johannesburg"
"Allendale;Phoenix"
"Brackenhurst;Alberton"
"Cape Town;"
"Durban;"
"Johannesburg;"
"Mayville;Durban"
"Phoenix;Durban"
"Sandton;Johannesburg"

,我想以最快的方式将其结构为层次结构,例如:

    约翰内斯堡
    • Alberton
      • Brackenhurst
    • 山顿
  • 开普敦
  • 德班
    • 凤凰
      • Allandale
    • Mayville

目前我有嵌套的循环和检查,但希望我能实现这与一个单一的LAMBDA查询?

上面提到的字符串都在List中

从c#的字符串构建层次结构

我准备了一个类似lambda的解决方案,但你应该真正考虑它是否比你现在的更可读/更高效:

Helper扩展方法:

public static class ChildrenGroupExtensions
{
    public static List<CityInfo> GetChildren(this IEnumerable<IGrouping<string, City>> source, string parentName)
    {
        var cities = source.SingleOrDefault(g => g.Key == parentName);
        if (cities == null)
            return new List<CityInfo>();
        return cities.Select(c => new CityInfo { Name = c.Name, Children = source.GetChildren(c.Name) }).ToList();
    }
}

助手类:

public class City
{
    public string Name { get; set; }
    public string Parent { get; set; }
}
public class CityInfo
{
    public string Name { get; set; }
    public List<CityInfo> Children { get; set; }
}

用法:

var groups = (from i in items
                let s = i.Split(new[] { ';' })
                select new City { Name = s[0], Parent = s[1] }).GroupBy(e => e.Parent);

var root = groups.GetChildren(string.Empty);

其中items是你的List<string>

您可以使用简单的辅助方法查看结果,如下所示:

private static void PrintTree(List<CityInfo> source, int level)
{
    if (source != null)
    {
        source.ForEach(c =>
        {
            Enumerable.Range(1, level).ToList().ForEach(i => Console.Write("'t"));
            Console.WriteLine(c.Name);
            PrintTree(c.Children, level + 1);
        });
    }
}

结果是:

Cape Town
Durban
        Mayville
        Phoenix
                Allendale
Johannesburg
        Alberton
                Brackenhurst
        Sandton

您没有指定任何特定的数据结构,所以我只是使用了一个名为Area的类,其本身包含一列子类。而且,它在2行linq中。也没有检查一个区域是否像代码一样是两个独立父节点的子节点。下面是我使用的测试代码(等号注释之间的相关行):

[TestFixture]
public class CitiesTest
{
    [Test]
    public void Test()
    {
        var strings = new List<string>
            {
                "Alberton;Johannesburg",
                "Allendale;Phoenix",
                "Brackenhurst;Alberton",
                "Cape Town;",
                "Durban;",
                "Johannesburg;",
                "Mayville;Durban",
                "Phoenix;Durban",
                "Sandton;Johannesburg"
            };
        //===================================================
        var allAreas = strings.SelectMany(x=>x.Split(';')).Where(x=>!string.IsNullOrWhiteSpace(x)).Distinct().ToDictionary(x=>x, x=>new Area{Name = x});
        strings.ForEach(area =>
            {
                var areas = area.Split(';');
                if (string.IsNullOrWhiteSpace(areas[1]))
                    return;
                var childArea = allAreas[areas[0]];
                if (!allAreas[areas[1]].Children.Contains(childArea))
                    allAreas[areas[1]].Children.Add(childArea);
                childArea.IsParent = false;
            });
        var result = allAreas.Select(x=>x.Value).Where(x => x.IsParent);
        //===================================================
    }
    public class Area
    {
        public string Name;
        public bool IsParent;
        public List<Area> Children { get; set; }
        public Area()
        {
            Children = new List<Area>();
            IsParent = true;
        }
    }
}