c# 从 LINQ 对象填充树视图 [英] c# populate treeview from LINQ object
问题描述
我有一个 linq 对象,我正在尝试使用 c# winforms 填充树视图.
I have a linq object that i'm trying to fill a treeview from using c# winforms.
样品
Column 1 Column 2 Column 3
Test 1 Item A Sub Item 1
Test 1 Item A Sub Item 2
Test 1 Item A Sub Item 3
Test 1 Item B Sub Item 1
Test 1 Item B Sub Item 2
Test 1 Item B Sub Item 3
并像填充树视图一样
Test 1 (CheckBox)
------Item A (CheckBox)
-------------Sub Item 1 (CheckBox)
-------------Sub Item 2 (CheckBox)
-------------Sub Item 3 (CheckBox)
------Item B (CheckBox)
-------------Sub Item 1 (CheckBox)
-------------Sub Item 2 (CheckBox)
-------------Sub Item 3 (CheckBox)
实现这一目标的最简单方法是什么?
What is the easiest way to achieve this?
谢谢喷
推荐答案
好吧,如果您执行以下查询:
Well, if you perform the following query:
var query = data.GroupBy(item => item.Column1)
.Select(group => group.GroupBy(item => item.Column2))
.Select(group => group.Select(innerGroup =>
innerGroup.GroupBy(item => item.Column3)));
您将首先按第 1 列分组所有项目,然后按第 2 和第 3 列分组,因此它已在树结构中.现在你只需要有 3 个嵌套的 for
循环来将项目添加到树视图中.
You will have all of the items grouped first by column1, then 2 and 3, so It's already in a tree structure. Now you just need to have 3 nested for
loops to add the items to the treeview.
foreach (var outermostGroup in query)
{
//add node for outermostGroup's key
foreach (var middleGroup in outermostGroup)
{
//add child node of the above node for middleGroup key
foreach (var innerGroup in middleGroup)
{
//add child node of the above node for innerGroup key
}
}
}
显然,此代码仅适用于具有固定(最大)深度的固定数量的列.如果您不知道列数并且可以具有任意深度,那么您需要一种完全不同的方法.
Clearly this code only works if there are a fixed number of columns with a fixed (max) depth. If you don't know the number of columns and can have an arbitrary depth then you'd need a fairly radically different approach.
这篇关于c# 从 LINQ 对象填充树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!