我喜欢 LinqPAD 中
.Dump()
扩展方法的强大功能,并希望将其用于可视化 Dictionary<string,string>
列表,其中键是列名,值是单个值。
基本上我想要实现的是:
而不是 (目前得到的)
.Dump()
扩展方法的强大功能,并希望将其用于可视化 Dictionary<string,string>
列表,其中键是列名,值是单个值。
基本上我想要实现的是:
而不是 (目前得到的)
你可以通过将它们转换为 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;
}
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();
listOfDictionaries.Select(d => new { One = d["one"], Two = d["two"] })
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){}
}
KVEntry
而非Dictionary<string,string>
,这使我能够正确地呈现我的对象,并且网格甚至可以导出到Excel。