我遇到了一个非常奇怪的问题,不知道该如何解决。
我有一个 IEnumerable<Dictionary<string,object>>
,它可以包含一个或多个 IEnumerable<Dictionary<string,object>>
。
现在,这个字典需要被导入到 DataTable 中。如果 IEnumberable<Dictionary<string,object>>
内部没有子项,则 DataTable 应该只包含一行,列名为字符串,RowData 为对象(在此情况下为字符串)。但是,如果存在子项,则 DataTable 应该包含与此子项相同数量的行,并且每行中都有来自父级的其他信息。
例如,父级字典具有以下值:
string, object --------------- Name, Mike LastName, Tyson
IEnumerable Dictionary 子项具有:
string, object ---------------- [0] ChildName, John ChildAge, 10
[1] ChildName, Tony ChildAge, 12
结果应该是:
Name LastName ChildName ChildAge -------------------------------------------- Mike Tyson John 10 Mike Tyson Tony 12
此外,Parent IEnumerable 可以有许多 children IEnumerable,但它们的大小都相同。
有人有解决方法吗?
static void Main(string[] args)
{
var child1 = new List<Dictionary<string, object>>();
var childOneDic = new Dictionary<string, object>
{
{ "ChildName", "John" },
{ "ChildAge", 10 }
};
child1.Add(childOneDic);
var child2 = new List<Dictionary<string, object>>();
var childTwoDic = new Dictionary<string, object>
{
{ "ChildName", "Tony" },
{ "ChildAge", 12 }
};
child2.Add(childTwoDic);
var parrent = new List<Dictionary<string, object>>();
var parrentDic = new Dictionary<string, object>
{
{ "Name", "Mike" },
{ "LastName", "Tyson" },
{ "child1", child1 },
{ "child2", child2 }
};
parrent.Add(parrentDic);
var table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("LastName");
table.Columns.Add("ChildName");
table.Columns.Add("ChildAge");
table = CreateTable(parrent, null, table);
}
static DataTable CreateTable(IEnumerable<Dictionary<string, object>> parrent,
DataRow row, DataTable table)
{
if (row == null)
{
row = table.NewRow();
}
foreach (var v in parrent)
{
foreach (var o in v)
{
if (o.Value.GetType().IsGenericType)
{
var dic = (IEnumerable<Dictionary<string, object>>) o.Value;
CreateTable(dic, row, table);
}
else
{
row[o.Key] = o.Value;
}
}
if (row.RowState == DataRowState.Added)
{
DataRow tempRow = table.NewRow();
tempRow.ItemArray = row.ItemArray;
table.Rows.Add(tempRow);
}
else
{
table.Rows.Add(row);
}
}
return table;
}