我想从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/

10-14 08:05