LINQ到基于分组填充树状 [英] LINQ to populate treeview based upon grouping
问题描述
我发现这个SO C#的答案,但似乎无法得到这个工作:
的 C#填充树视图从LINQ对象
I found this C# answer on S.O., but can't seem to get this working: c# populate treeview from LINQ object
在我的情况下,假设我有一个名单(共Report_Data )
其中,例如,看起来是这样的:
In my case, suppose I have a List(Of Report_Data)
which, for example, looks like this:
Var1 Var2
V1 Sub Item 1
V1 Sub Item 2
V1 Sub Item 3
V2 Sub Item 1
V2 Sub Item 2
V3 Sub Item 1
和我期待使用LINQ来填充一个TreeView的样子:
And I'm looking to use LINQ to fill a treeview to look like:
V1 (CheckBox)
-------Sub Item 1 (CheckBox)
-------Sub Item 2 (CheckBox)
-------Sub Item 3 (CheckBox)
V2 (CheckBox)
-------Sub Item 1 (CheckBox)
-------Sub Item 2 (CheckBox)
V3 (CheckBox)
-------Sub Item 1 (CheckBox)
所以,在我的树视图填充程序中,我创建了以下内存查询:
So, in my Treeview-filling routine, I create the following in-memory query:
Dim GroupedReports = From Rpt As Report_Data In ReportsToBeProcessed
Group Rpt By Rpt.Var1 Into Group
然后,我以为我可以通过组和循环再组合的对象来填充树视图 - 线沿线的东西:
And then I thought I could loop through the Groups and then the grouped objects to fill the treeview - something along the lines of:
For Each Grp As Object In GroupedReports
... Add Parent node ...
For Each Rpt As Report_Data In Grp
... Add Child Node ...
Next
Next
首先,我不知道如何使用的数据类型为我的 GRP
变量,其次它似乎并不奏效......结果
我如何正确地做到这一点?
Firstly, I don't know what data-type to use for my Grp
variable and secondly it doesn't seem to be working...
How do I do this correctly?
推荐答案
像这样的东西,你的意思是?
Something like this, you mean?
(对不起,从来不写VB了,所以最好我能做的就是C#)
(sorry, never write VB anymore, so best I can do is C#)
var grped =
from report in reports
group report by report.Var1 into grp
select grp;
var treeView = new System.Windows.Forms.TreeView();
foreach(var grouping in grped)
{
var nodeFor = treeView.Nodes.Add(grouping.Key);
foreach(var item in grouping)
{
var subitem = nodeFor.Nodes.Add(item.Var2);
}
}
编辑:
中的按组构建返回一组 IGrouping< TKEY的,TValue>
- 你可以种认为这是一个键值对,关键是你通过分组的事情,该值是匹配该密钥的所有元素
The "group by" construct returns a set of IGrouping<TKey, TValue>
- you can kind of think of this as a key-value pair, with the key being the thing you grouped by, and the value being all elements that matched that key.
下面是VB.Net代码,我相信:
Here is the VB.Net code I believe:
Dim grped = From report In reports
Group report By report.Var1 into grp
Select grp
Dim treeView as New System.Windows.Forms.TreeView()
For Each grouping In grped
Dim nodeFor = treeView.Nodes.Add(grouping.Key)
For Each item In grouping
Dim subitem = nodeFor.Nodes.Add(item.Var2)
Next
Next
这篇关于LINQ到基于分组填充树状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!