[英]Writing nested collection to datatable c#
Basically I have a class like this:基本上我有一个像这样的 class :
public class A
{
public A()
{
}
public Guid Key { get; set; }
public long PrimaryId { get; set; }
public bool IsActive { get; set; }
public Dictionary<string, string> Dict { get; set; }
public Dictionary<int, string> Dict1 { get; set; }
}
Based on the answer here , I can use TypeDescriptor which works great for non-nested collections.根据此处的答案,我可以使用非常适用于非嵌套 collections 的 TypeDescriptor。 For nested collections and dictionary I use a method like this:对于嵌套的 collections 和字典,我使用这样的方法:
private static bool IsEnumerable(PropertyInfo pi)
{
// note: we could also use IEnumerable (but string, arrays are IEnumerable...)
return typeof(ICollection).IsAssignableFrom(pi.PropertyType);
}
private static bool IsDictionary(PropertyInfo pi)
{
return pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>);
}
However, if someone can help with a method which converts a generic list to DataTable.但是,如果有人可以帮助使用将通用列表转换为 DataTable 的方法。 That will be great.那挺棒的。
Check this Coverting List of Dictionary to DataTable检查这个字典到数据表的覆盖列表
static DataTable ToDataTable(List<Dictionary<string, int>> list)
{
DataTable result = new DataTable();
if (list.Count == 0)
return result;
var columnNames = list.SelectMany(dict=>dict.Keys).Distinct();
result.Columns.AddRange(columnNames.Select(c=>new DataColumn(c)).ToArray());
foreach (Dictionary<string,int> item in list)
{
var row = result.NewRow();
foreach (var key in item.Keys)
{
row[key] = item[key];
}
result.Rows.Add(row);
}
return result;
}
static void Main(string[] args)
{
List<Dictionary<string, int>> it = new List<Dictionary<string, int>>();
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("a", 1);
dict.Add("b", 2);
dict.Add("c", 3);
it.Add(dict);
dict = new Dictionary<string, int>();
dict.Add("bob", 34);
dict.Add("tom", 37);
it.Add(dict);
dict = new Dictionary<string, int>();
dict.Add("Yip Yip", 8);
dict.Add("Yap Yap", 9);
it.Add(dict);
DataTable table = ToDictionary(it);
foreach (DataColumn col in table.Columns)
Console.Write("{0}\t", col.ColumnName);
Console.WriteLine();
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
Console.Write("{0}\t", row[column].ToString());
Console.WriteLine();
}
Console.ReadLine();
}
And the output looks like... output 看起来像......
a b c bob tom Yip Yip Yap Yap
1 2 3
34 37
8 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.