gpt4 book ai didi

c# - 从 DataTable 构建嵌套列表

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:46 27 4
gpt4 key购买 nike

我想从 DataTable 返回嵌套列表。所以我正在为以下场景寻找 LINQ 查询

 DataTable table = new DataTable();
table.Columns.Add("Header", typeof(string));
table.Columns.Add("RowHeader", typeof(string));
table.Columns.Add("ItemHeader", typeof(string));
table.Columns.Add("Items", typeof(string));

table.Rows.Add("Header1", "RowHeader1", "Item Header1", "Item1, Item2, Items3");
table.Rows.Add("Header1", "RowHeader1", "Item Header2", "Item1, Item2, Items3");
table.Rows.Add("Header1", "RowHeader2", "Item Header3", "Item1, Item2, Items3");
table.Rows.Add("Header2", "RowHeader3", "Item Header4", "Item1, Item2, Items3");

注意:这里的项目用逗号(,)分隔

  public class HeaderClass
{
public string Header { get; set; }
public IEnumerable<RowHeaderClass> RowHeader{ get; set; }
}

public class RowHeaderClass
{
public string Header { get; set; }
public IEnumerable<RowItemsClass> RowItems{ get; set; }
}

public class RowItemsClass
{
public string Item1{ get; set; }
public string Item2{ get; set; }

}

提前致谢。

最佳答案

你的类定义似乎不完整 - 你似乎缺少变量来保存 ItemHeader 和额外的项目,但鉴于你提供的内容,你可以通过行:

List<HeaderClass> x = (from row in table.AsEnumerable()
group row by row.Field<string>("Header") into hdr
select new HeaderClass
{
Header = hdr.First().Field<string>("Header"),
RowHeader = (from hdrrow in hdr
group hdrrow by hdrrow.Field<string>("RowHeader") into row
select new RowHeaderClass
{
Header = row.First().Field<string>("RowHeader"),
RowItems = from itemrow in row
select new RowItemsClass
{
Item1 = itemrow.Field<string>("Items").Split(',')[0],
Item2 = itemrow.Field<string>("Items").Split(',')[1]
}
}).ToList()

}).ToList();

希望这至少能帮助您朝着正确的方向前进!

关于c# - 从 DataTable 构建嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23224186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com