我想从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; }
}
提前致谢。
答案 0 :(得分:1)
您的类定义似乎并不完整 - 您似乎缺少保存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();
希望这至少可以帮助你朝着正确的方向前进!