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

3
我喜欢 LinqPAD 中 .Dump() 扩展方法的强大功能,并希望将其用于可视化 Dictionary<string,string> 列表,其中键是列名,值是单个值。

基本上我想要实现的是:

Table Visualisation

而不是 (目前得到的)

Dictionary entries

4个回答

10

你可以通过将它们转换为 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;
}

有两列:“one”和“two”的List<ExpandoObject>


这是目前我能得到的最佳结果,谢谢。唯一的问题是,如果您使用“将结果导出到DataGrid”选项,则无法获取datagrid,而是一组项目... - Alexander Galkin

6
你可以创建一个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;       
}

您可以像这样做:
 listOfDictionaries.ToDataTable().Dump();

2
如何只是简单的呢?
listOfDictionaries.Select(d => new { One = d["one"], Two = d["two"] })

是的,我这样做是为了生成第一张图片,但我不想每次我的键(例如表格的列)发生变化时都更改此转换方法。 - Alexander Galkin

1
我找到了正确的影响列名的方法:根据LinqFAQ,我们需要实现LINQPad.ICustomMembershipProvider。对于Dictionary<string,string>类型的变量,其中Keys是列名,Values是实际值,只需将下面的代码添加到My Extesions中即可:
public class KVEntry : Dictionary<string,string>, LINQPad.ICustomMemberProvider
{
    IEnumerable<string> ICustomMemberProvider.GetNames() 
    {
        return Keys;
    }

    IEnumerable<Type> ICustomMemberProvider.GetTypes()
    {
        return Enumerable
                .Repeat(typeof(string),Count);
    }

    IEnumerable<object> ICustomMemberProvider.GetValues()
    {
        return Values;
    } 

    public KVEntry(Dictionary<string,string> data) : base(data){}
}

现在在LINQPad查询中,必须使用KVEntry而非Dictionary<string,string>,这使我能够正确地呈现我的对象,并且网格甚至可以导出到Excel。

Correct Grid

很不幸,这对于“结果转换为数据网格”模式无效,在此模式下,LINQPad(可能是故意的)完全忽略了ICustomMemberProvider。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接