您好我有两个列表,一个是父列表,另一个是子列表我需要将两个列表中包含的数据加载到单个Datatable是否有办法做到这一点
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
答案 0 :(得分:1)
有什么问题?你可以使用一个循环:
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);
}
}
答案 1 :(得分:1)
你可能想要使用microsofts如何创建一个副本到datable方法的例子在这里显示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();