我正在对datatable执行SQL查询。查询可以返回多个列。结果是键值格式并表示分层数据。请参见下面的屏幕截图
图像显示3个部分。首先是数据,然后是数据的层次表示和JSON等价物。
目前图像显示4级数据,但我们可以有6-7级数据。格式将保持不变,但列数可以更改。
如何使用C#获得所需的结果? ?我知道这是基本的编程,但我很难用它。
答案 0 :(得分:5)
使用您在示例中显示的固定级别层次结构,可以使用LINQ query with grouping为JSON生成树结构。以下是具有三级层次结构的示例:
static void Main(string[] args)
{
var data = new List<Data>
{
new Data("Food", "1_g", "beverage", "2_b", "hot", "3_h"),
new Data("Food", "1_g", "beverage", "2_b", "cold", "3_c"),
new Data("Food", "1_g", "fruit", "2_f", "juicy", "3_j"),
new Data("Food", "1_g", "fruit", "2_f", "solid", "3_s"),
new Data("Food", "1_g", "cookie", "2_c", "chocolate", "3_cho"),
};
var tree = from l1 in data
group l1 by new { key = l1.Key_L1, name = l1.L1 } into group1
select new
{
key = group1.Key.key,
name = group1.Key.name,
children = from l2 in group1
group l2 by new { key = l2.Key_L2, name = l2.L2 } into group2
select new
{
key = group2.Key.key,
name = group2.Key.name,
children = from l3 in group2
select new { key = l3.Key_L3, name = l3.L3 }
}
};
var serializer = new JavaScriptSerializer();
Console.WriteLine(serializer.Serialize(tree));
Console.ReadLine();
}
class Data
{
public Data(string l1, string k1, string l2, string k2, string l3, string k3)
{
L1 = l1; Key_L1 = k1;
L2 = l2; Key_L2 = k2;
L3 = l3; Key_L3 = k3;
}
public string L1 { get; set; }
public string Key_L1 { get; set; }
public string L2 { get; set; }
public string Key_L2 { get; set; }
public string L3 { get; set; }
public string Key_L3 { get; set; }
}
以上是使用POCO的技术的一个工作示例。
你提到“数据表”;我认为这是指.NET DataTable
class?如果是这样,您可以使用LINQ查询DataTable
。您只需要使用DataSetExtensions将其转换为可枚举。请参阅:LINQ query on a DataTable
然后在LINQ语句中,将列表替换为数据表.AsEnumerable()
,并将属性引用替换为.Field<string>("")
。像这样:
DataTable dt = // load data table
var tree = from l1 in dt.AsEnumerable()
group l1 by new { key = l1.Field<string>("Key_L1"), name = l1.Field<string>("L1") } into group1
select new
{
// etc.
};
对于可变数量的列,您必须使用递归方法,如下所示:
var tree = Descend(dt.AsEnumerable(), 1, 3);
private static System.Collections.IEnumerable Descend(IEnumerable<DataRow> data, int currentLevel, int maxLevel)
{
if (currentLevel > maxLevel)
{
return Enumerable.Empty<object>();
}
return from item in data
group item by new
{
key = item.Field<string>("Key_L" + currentLevel),
name = item.Field<string>("L" + currentLevel)
} into rowGroup
select new
{
key = rowGroup.Key.key,
name = rowGroup.Key.name,
children = Descend(rowGroup, currentLevel + 1, maxLevel)
};
}
需要注意的一点是,此方法会在叶节点上创建一个空的children
集合。