通过linq将DataTable转换为nestead类

时间:2016-11-12 11:09:23

标签: c# linq datatable inner-classes

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

[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如下:

 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中的数据转换为我的班车。 任何帮助将不胜感激 更新: 对于使用建议,我需要使用下面的代码更改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);

1 个答案:

答案 0 :(得分:1)

使用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#命名约定