在LinqPAD中将字典列表可视化为数据网格?

Ale*_*kin 3 c# dictionary visualization linqpad

我喜欢.Dump()LinqPAD中扩展方法的强大功能,并希望用它来显示Dictionary<string,string>一个数据网格列表,其中键是列名,值分别是单个值.

基本上我想要实现的是:

表格可视化

而不是(目前正在)

字典条目

Tim*_* S. 6

您可以通过将它们变为ExpandoObjects:

listOfDictionaries.Select(x => x.ToExpando()).ToList().Dump();


public static ExpandoObject ToExpando(this IDictionary<string, string> dict)
{
    var expando = new ExpandoObject();
    var expandoDic = (IDictionary<string, object>)expando;
    foreach (var kvp in dict)
        expandoDic.Add(kvp.Key, kvp.Value);
    return expando;
}
Run Code Online (Sandbox Code Playgroud)

列出<ExpandoObject>,其中包含两列:


sgm*_*ore 5

您可以创建一个DataTable,它应该在两种模式下正确显示.

用扩展方法就好了

public static DataTable ToDataTable<T>(this IEnumerable<Dictionary<string,T>> source)
{
    DataTable table = new DataTable(); 
    foreach(var dict in source)
    {
        var dr = table.NewRow();
        foreach(var entry in dict)
        {
            if (!table.Columns.Contains(entry.Key))
                table.Columns.Add(entry.Key, typeof(T));
            dr[entry.Key] = entry.Value;
        }
        table.Rows.Add(dr);
    }

    return table;       
}
Run Code Online (Sandbox Code Playgroud)

然后你可以做类似的事情

 listOfDictionaries.ToDataTable().Dump();
Run Code Online (Sandbox Code Playgroud)