I am creating an application for chatting in WPF(C#.net). I have created a class User with following attributes: 1.Company_name 2.Branch 3.Designation 4.User_name I am getting the list of objects of class user. I want to display the users in treeview as:
Company name1 -Branch1 -:Designation1 *User name1 *User name2 -Branch2 -:Designation1 *User name3 -:Designation2 *User name4
when user list is refreshed, the tree structure will reloaded. I want to create this tree structure considering users with same parent. I am getting the user list at run time when a new user logs in. How to create such tree? I want to know, how to create such treeview using "ViewMode开发者_运维百科l and display it in WPF window"??
Your question is not clear enough, I guess that your question is about how to create a hierarchy from a list of users by grouping on every property.
for that purpose you may use linq's grouping functionality. Here is a sample for the first level, you may repeat it in itself to create a hierarchy:
var users = new[] {
new {
CompanyName = "c1",
Branch = "b1",
Destination = "d1",
UserName= "u1",
}, new {
CompanyName = "c1",
Branch = "b1",
Destination = "d1",
UserName= "u1",
}, new {
CompanyName = "c1",
Branch = "b1",
Destination = "d1",
UserName= "u1",
}, new {
CompanyName = "c2",
Branch = "b1",
Destination = "d2",
UserName= "u2",
},
};
var data = from u in users
group u by u.CompanyName into ug
select new { Node = ug.Key, Childs = ug };
foreach (var i in data)
{
Console.WriteLine(i.Node);
foreach (var node in i.Childs)
{
Console.WriteLine("\t" + node.UserName);
}
}
And this is the code with the nested groupings:
var users = new[] {
new {
CompanyName = "c1",
Branch = "b3",
Destination = "d1",
UserName= "u1",
}, new {
CompanyName = "c1",
Branch = "b1",
Destination = "d1",
UserName= "u1",
}, new {
CompanyName = "c1",
Branch = "b1",
Destination = "d1",
UserName= "u1",
}, new {
CompanyName = "c2",
Branch = "b1",
Destination = "d2",
UserName= "u2",
},
};
var data = from u1 in users
group u1 by u1.CompanyName into gByCompanyName
select new
{
Node = gByCompanyName.Key,
Childs = from u2 in gByCompanyName
group u2 by u2.Branch into gByBranch
select new
{
Node = gByBranch.Key,
Childs = from u3 in gByBranch
group u3 by u3.Destination into gByDestination
select new
{
Node = gByDestination.Key,
Childs = from u4 in gByDestination
select new { Node = u4.UserName }
}
}
};
foreach (var n1 in data)
{
Console.WriteLine(n1.Node);
foreach (var n2 in n1.Childs)
{
Console.WriteLine("\t" + n2.Node);
foreach (var n3 in n2.Childs)
{
Console.WriteLine("\t\t" + n3.Node);
foreach (var n4 in n3.Childs)
{
Console.WriteLine("\t\t\t" + n4.Node);
}
}
}
}
Console.ReadLine();
I hope this helps.
精彩评论