我想编写一个应用程序来按照主机名的顺序解析树视图中的短链接:
Input:
bit.ly/sh125ad
adf.ly/sh1d5ad
bit.ly/sh1d5ad
adf.ly/sh125ad
adf.ly/sh12had
Output:
adf.ly
adf.ly/sh1d5ad
adf.ly/sh125ad
adf.ly/sh12had
bit.ly
bit.ly/sh125ad
bit.ly/sh1d5ad
在我编写解析部分之后:
List<string> links = linkField.Text.Split('\n').ToList();
我不知道如何在treeView.Nodes
中添加父节点,然后添加Child节点。
我的尝试是:
foreach (string link in links)
{
Uri url = new Uri(link);
if (!treeView.Nodes.Contains(new TreeNode(url.Host)))
treeView.Nodes.Add(new TreeNode(url.Host));
}
但如果我想添加链接,我就找不到第一个TreeNode,因为它的子节点
答案 0 :(得分:1)
这有点乱,但很快就可以做到你想要的。首先创建一个类来保存每个uniqe域及其URL:
public class ShortLink
{
public string DomainName { get; set; }
public List<string> UrlList;
public ShortLink(string domainName)
{
DomainName = domainName;
UrlList = new List<string>();
}
public void AddUrl(string url)
{
if(!UrlList.Contains(url))
UrlList.Add(url);
}
public string GetFullUrl(int indexOfUrlInList)
{
return DomainName + "/" + UrlList[indexOfUrlInList];
}
//Add other methods like remove and stuff
}
假设您的表单有一个名为treeView1
的treview,请尝试以下代码:
public partial class Form1 : Form
{
private List<string> _links = new List<string>(new []{
"bit.ly/sh125ad",
"adf.ly/sh1d5ad",
"bit.ly/sh1d5ad",
"adf.ly/sh125ad",
"adf.ly/sh12had"
});
private List<ShortLink> _shortLinks = new List<ShortLink>();
public Form1()
{
InitializeComponent();
PopulateTreeView();
}
private void PopulateTreeView()
{
//Make the dictionary
foreach (var link in _links)
{
var parts = link.Split('/');
var domainPart = parts[0];
if (!_shortLinks.Contains(_shortLinks.FirstOrDefault(x => x.DomainName == domainPart)))
{
var shortLink = new ShortLink(domainPart);
_shortLinks.Add(shortLink);
}
}
foreach (var link in _links)
{
var parts = link.Split('/');
var domainPart = parts[0];
var urlPart = parts[1];
//find a ShortLink in the list we made that matches this domainpart
var shortLink = _shortLinks.FirstOrDefault(x => x.DomainName == domainPart);
//if its not null, we add the url part to taht!
if(shortLink != null)
shortLink.AddUrl(urlPart);
//now we have all domains and parts
}
//Populate treeview
foreach (var shortLink in _shortLinks)
{
var parentNode = new TreeNode(shortLink.DomainName);
var childNodes = new List<TreeNode>();
//add all the links in the current shortLink to the list of treenodes
foreach (var link in shortLink.UrlList)
{
childNodes.Add(new TreeNode(link));
}
//now time to add child notes to parent node
parentNode.Nodes.AddRange(childNodes.ToArray());
treeView1.Nodes.Add(parentNode);
}
}
}
<强>更新强>
我刚刚意识到你的问题实际上是关于寻找父节点。请参阅以下方法:
private void AddToTreeView(string domain, string link)
{
foreach (TreeNode node in treeView1.Nodes)
{
if (node.Text == domain)
{
node.Nodes.Add(link);
}
}
}
当然,您可以在foreach循环中创建Node
时创建完整的节点详细信息。您可以为每个节点设置Name
和Tag
等fied,以供进一步使用!
您也可以继承TreeNode
,并拥有自己的自定义字段。