【问题标题】:Nested Datatable to nested list嵌套数据表到嵌套列表
【发布时间】:2017-11-23 08:37:33
【问题描述】:

我正在获取包含可以是 1,2 或 4 的数据表的数据集。

我正在将其翻译成如下所示的列表类。

   public class test
    {
           public int id  { get; set; }
           public int name { get; set; }
           public List<test> LstTest {get;set;}
    }

例如,如果我将 3 个数据表放入数据集中,我假设从第一个数据表创建测试类列表,其中包含需要从数据表 2 填充的另一个列表(LstTest),并且此列表中的每个对象再次包含需要从数据表 3 中填充的 LstTest。

您能否为此提供解决方案。我可以静态地做到这一点,但问题是这需要是动态的,因为数据表的数量可以是任意的,例如2,3,4等

非常感谢任何帮助。

【问题讨论】:

    标签: c# datatable dataset


    【解决方案1】:

    未经测试,但如果我正确理解您的要求,应该可以工作:

    public static List<test> GetTestLists(DataSet ds)
    {
        var allLists = new Dictionary<int, List<test>>();
    
        // reverse loop necessary for efficient algorithm
        for (int i = ds.Tables.Count -1; i >= 0; i--)
        {
            List<test> childList;
            bool hasChildren = allLists.TryGetValue(i + 1, out childList);
            var testList = new List<test>();
            DataTable tbl = ds.Tables[i];
    
            foreach (DataRow row in tbl.Rows)
            {
                var t = new test
                {
                    id = row.Field<int>("Id"),
                    name = row.Field<int>("name") // int for name ??
                };
                if (hasChildren)
                    t.LstTest = childList;
                testList.Add(t);
            }
            allLists.Add(i, testList);
        }
    
        return allLists.TryGetValue(0, out List<test> parentList) ? parentList : null;
    }
    

    我猜int name 应该是string name。也申请.NET capitalization conventions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2018-08-02
      • 1970-01-01
      相关资源
      最近更新 更多