[英]Load multiple lists in to one datatable
Hi I have two lists one is parent list and other one is child list And I need to load the data contain in both list to single Datatable is there are way to do that 嗨我有两个列表一个是父列表,另一个是子列表我需要加载两个列表中的数据包含单个数据表是否有办法做到这一点
public class Country
{
string Name;
string Countrycode
list<Company> Companies=new list<Company>();
}
public class Company
{
string ComapnyName;
string Address1;
string Address2;
String Owner;
}
when creating table it must be like this 在创建表时,它必须是这样的
Name Countrycode ComapnyName Address1 Address2 Owner
USA 001 Apple Whereever null Jobbs
Japan 002 Sony Whereever null unknown
What's the problem? 有什么问题? You can use a loop: 你可以使用一个循环:
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);
}
}
You probably want to use microsofts example of how to create a copy to datable method show here MSDN 您可能想要使用microsofts示例如何创建一个副本到数据方法显示在这里MSDN
You can then do the following 然后,您可以执行以下操作
Country.SelectMany(x => x.Companies
.Select(y => new {
x.Name,
x.CountryCode,
y.ComapnyName,
y.Address1,
y.Address2,
y.Owner
} )).CopyToDataTable();
PS copied the spelling of Comapny name not sure if you mean this! PS复制Comapny名称的拼写不确定你的意思是这个!
Update to deal with Companies being null 更新以处理公司为空
If the companies property could be null: 如果公司财产可能为空:
Country.SelectMany(x => (x.Companies ?? Enumerable.Empty<Company>())
.Select(y => new {
x.Name,
x.CountryCode,
y.ComapnyName,
y.Address1,
y.Address2,
y.Owner
} )).CopyToDataTable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.