As i mentioned in the comment to the question you did not provide enough information. Nevertheless...
You can use
Linq[
^] to get the list of products and its varances. Have a look at example:
public class Variance
{
private int pid = 0;
private string c = string.Empty;
public Variance(int _pid, string _c)
{
pid = _pid;
c = _c;
}
public int ProdId
{
get{return pid;}
set{pid = value;}
}
public string Color
{
get{return c;}
set{c = value;}
}
}
public class Product
{
private int pid = 0;
private string sname = string.Empty;
private List<Variance> cvariances = null;
public Product(int _pid, string _sname, List<Variance> _cvariances)
{
pid = _pid;
sname = _sname;
cvariances = _cvariances;
}
public int ProdId
{
get{return pid;}
set{pid = value;}
}
public string Name
{
get{return sname;}
set{sname = value;}
}
public List<Variance> ProductVariances
{
get{return cvariances;}
set{cvariances = value;}
}
}
List<product> products = new List<product>()
{
new Product(1, "GummiBear", new List<variance>()
{
new Variance(1, "black"),
new Variance(1, "red"),
new Variance(1, "white")
}),
new Product(2, "CellPhone", new List<variance>()
{
new Variance(2, "blue"),
new Variance(2, "gold")
})
};
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("ProdId", Type.GetType("System.Int32"));
dt.Columns.Add(dc);
dc = new DataColumn("Name", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Color", Type.GetType("System.String"));
dt.Columns.Add(dc);
var result = from v in products.SelectMany(p=>p.ProductVariances.Select(pv=>pv))
join p in products on v.ProdId equals p.ProdId
select new object[]
{
p.ProdId,
p.Name,
v.Color
};
foreach (var r in result)
{
dt.Rows.Add(r);
}
Result:
ProdId Name Color
1 GummiBear black
1 GummiBear red
1 GummiBear white
2 CellPhone blue
2 CellPhone gold
Note: the definition of classes has been changed.
You can use
CopyToDataTable extension method[
^] to create
DataTable
object in simpler manner.