سؤال

I love the might of the .Dump() extension method in LinqPAD and would like to use it to visualize a list of Dictionary<string,string> as a data grid, where the keys are column names and values are single values respectively.

Basically what I want to achieve is:

Table Visualisation

instead of (currently getting)

Dictionary entries

هل كانت مفيدة؟

المحلول 2

You could create a DataTable which should display in both modes correctly.

With an extension method like

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;       
}

you can then do something like

 listOfDictionaries.ToDataTable().Dump();

نصائح أخرى

You can get this by turning them into 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;
}

List<ExpandoObject> with two columns: "one" and "two"

how about just

listOfDictionaries.Select(d => new { One = d["one"], Two = d["two"] })

I found the correct way to influence the column names: according to LinqFAQ one has to implement LINQPad.ICustomMembershipProvider.

For Dictionary<string,string> with Keys being column names and Values actual values one just has to add the following code to 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){}
}

Now one has to use KVEntry instead of Dictionary<string,string> in LINQPad queries. This allows me to correctly render my objects and the grid can even be exported to Excel.

Correct Grid

Unfortunately, this doesn't work for Results to Data Grids mode, where LINQPad (probably by design) just ignores the ICustomMemberProvider altogether.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top