将多个列表加载到一个数据表中

本文关键字:一个 数据表 列表 加载 | 更新日期: 2023-09-27 18:33:23

嗨,我有两个列表,一个是父列表,

另一个是子列表,我需要将两个列表中包含的数据加载到单个数据表中,有没有办法做到这一点

public class Country
{
  string Name;
  string Countrycode
  list<Company> Companies=new list<Company>(); 
}
public class Company
{
  string ComapnyName;
  string Address1;
  string Address2;
  String Owner; 
} 

创建表时必须像这样

Name       Countrycode  ComapnyName   Address1    Address2   Owner              
USA          001          Apple       Whereever   null       Jobbs  
Japan        002          Sony        Whereever   null       unknown

将多个列表加载到一个数据表中

有什么问题?您可以使用循环:

DataTable tblCountries = new DataTable();
// add all columns ...
foreach(Country c in allCountries)
{
    if(c.Companies.Any())
    {
        foreach(var company in c.Companies)
        {
            var row = tblCountries.Rows.Add();
            row.SetField("Name", c.Name);
            row.SetField("Countrycode", c.Countrycode);
            row.SetField("CompanyName", company.CompanyName);
            // add the other company fields ...
        }
    }
    else  // add just the country and let the company cells be null
    {
        var row = tblCountries.Rows.Add();
        row.SetField("Name", c.Name);
        row.SetField("Countrycode", c.Countrycode);
    }
}

您可能希望使用如何创建副本到可处理方法的 Microsoft 示例在此处显示 MSDN

然后,您可以执行以下操作

Country.SelectMany(x => x.Companies
                         .Select(y => new { 
                                            x.Name,
                                            x.CountryCode,
                                            y.ComapnyName,
                                            y.Address1,
                                            y.Address2,
                                            y.Owner
                                          } )).CopyToDataTable();

PS复制了Comapny名称的拼写,不确定您是否是这个意思!

更新以处理公司为空

如果公司属性可能为空:

Country.SelectMany(x => (x.Companies ?? Enumerable.Empty<Company>())
                         .Select(y => new { 
                                            x.Name,
                                            x.CountryCode,
                                            y.ComapnyName,
                                            y.Address1,
                                            y.Address2,
                                            y.Owner
                                          } )).CopyToDataTable();