C#将列表转换为层次结构
嘿嘿, 我目前正在从事一个c#wpf项目,我想从一个线性项目列表中动态填充一个树状视图 我的出发点是这篇关于codeproject的文章: John Smith展示了如何在TreeView中使用HierarchalDataTemplate。到目前为止,这是可行的。我的问题是从项目的线性列表中动态生成层次结构树。我已尝试调整此处找到的解决方案 这里呢 但不知何故,我没有成功 我的item类如下所示:C#将列表转换为层次结构,c#,list,hierarchy,C#,List,Hierarchy,嘿嘿, 我目前正在从事一个c#wpf项目,我想从一个线性项目列表中动态填充一个树状视图 我的出发点是这篇关于codeproject的文章: John Smith展示了如何在TreeView中使用HierarchalDataTemplate。到目前为止,这是可行的。我的问题是从项目的线性列表中动态生成层次结构树。我已尝试调整此处找到的解决方案 这里呢 但不知何故,我没有成功 我的item类如下所示: public class Item { public string Name { g
public class Item
{
public string Name { get; set; }
public ItemPath[] ParentPath { get; set; }
public ItemPath[] Path { get; set; }
}
ItemPath类
public class ItemPath
{
public int Level { get; set; }
public string Name { get; set; }
}
目标层次类
public class ItemTree
{
public string Name { get; set; }
public Item Item { get; set; }
public List<ItemTree> ChildTree { get; set; }
}
不知何故,我认为使用数组作为路径和父路径不是一个好主意。但是它反映了一个绝对路径(与文件系统中的文件路径相当)。你想过用它来构建层次结构吗?嘿,不,我从来没有听说过。也许我得学点新东西。你知道一个很好的例子吗?不管怎样,只需要向下滚动wiki文章:-)用于将输入转换为层次列表的数据格式是什么?您创建的
Item
和ItemPath
类型是否有助于构建树?您创建的Item和ItemPath类型是否有助于构建树?->对
var items = new List<Item>()
{
new Item()
{
Name = "item 0",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
}
},
new Item()
{
Name = "item 1",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
new Item()
{
Name = "item 2",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Violet", Level = 2 },
}
},
new Item()
{
Name = "item 3",
Path = new ItemPath[]
{
new ItemPath() { Name = "Blue", Level = 1 },
new ItemPath() { Name = "Black", Level = 2 },
}
},
new Item()
{
Name = "item 4",
Path = new ItemPath[]
{
new ItemPath() { Name = "Blue", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
new Item()
{
Name = "item 5",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
};
// class to create dummy data as described above
var dummyData = new DummyData();
var items = dummyData.CreateTier2DummyList();
var cat = items.Select(r => new ItemTree()
{
Path = r.Path,
Item = r,
// parent path is generated dynamically
ParentPath = r.Path.Reverse().Skip(1).Reverse().ToArray(),
}).ToList();
var lookup = cat.ToLookup(c => c.ParentPath);
foreach (var c in cat)
{
if (lookup.Contains(c.Path))
c.ChildTree = lookup[c.ParentPath].ToList();
}