通过 linq 将 DataTable 转换为 nestead Class

Convert DataTable to nestead Class by linq

我有一个嵌套的 class 定义如下:

[XmlRoot()]
public class cars
{
    [XmlElement(ElementName="car")]
    public car[] carList { get; set; }
}
public class car
{
    [XmlElement(ElementName = "manufacture")]
    public string manufacture { get; set; }
    [XmlElement(ElementName = "models")]
    public models modelList { get; set; }
}
public class models
{
    [XmlElement(ElementName = "model")]
    public model[] modelList { get; set; }
}
public class model
{
    [XmlElement(ElementName = "name")]
    public string name { get; set; }
    [XmlElement(ElementName = "color")]
    public string color { get; set; }
}

我有一个数据表如下:

 DataTable dt = new DataTable();
    dt.Columns.Add("Manufacture");
    dt.Columns.Add("ModelName");
    dt.Columns.Add("Color");

    Object[] rows = { 
        new Object[]{"P1","405","1,6"},
        new Object[]{"P1","406","1,7"},
        new Object[]{"P2","407","1,8"},
        new Object[]{"P2","408","1,9"}
    };
    dt.Rows.Add(rows);

我想将 DataTable 中的数据转换为我的 class 汽车。 任何帮助将不胜感激。
更新: 为了使用建议,我需要用下面的代码更改 Rows.Add,否则,我只会在结果中得到对象。

            DataRow dr= dt.NewRow();
        dr["Manufacture"] = "Peugeot1";
        dr["ModelName"] = "405";
        dr["Color"] = "1,6";
        dt.Rows.Add(dr);
        DataRow dr2 = dt.NewRow();
        dr2["Manufacture"] = "Peugeot1";
        dr2["ModelName"] = "406";
        dr2["Color"] = "1,7";
        dt.Rows.Add(dr2);
        DataRow dr3 = dt.NewRow();
        dr3["Manufacture"] = "Peugeot2";
        dr3["ModelName"] = "405";
        dr3["Color"] = "1,6";
        dt.Rows.Add(dr3);

使用 GroupByManufacture 对所有行进行分组,然后为每个组项目一个新的 Car。要填充 ModelList 属性,请在组中使用 Select

var result = (from row in dt.AsEnumerable()
              group row by row.Field<string>("Manufacture") into grouping
              select new Car
              {
                  Manufacture = grouping.Key,
                  ModelList = grouping.Select(item => new Model
                  {
                      Name = item.Field<string>("ModelName"),
                      Color = item.Field<string>("Color")
                  }).ToArray()
              }).ToList();

您还可以将方法语法与 GroupBy 重载一起使用,您可以在其中指定选择器谓词:

var result = dt.AsEnumerable()
               .GroupBy(row => row.Field<string>("Manufacture"),
                        row => new Model
                        {
                            Name = row.Field<string>("ModelName"),
                            Color = row.Field<string>("Color")
                        })
               .Select(group => new Car
               {
                   Manufacture = group.Key,
                   ModelList = group.ToArray()
               }).ToList();

请注意,我更改了 类 和 属性 名称以匹配 C# 命名约定