我喜欢LinqPAD中.Dump()
扩展方法的可能性,并且希望用它来将Dictionary<string,string>
列表可视化为数据网格,其中键是列名,值分别是单个值。将字典列表可视化为LinqPAD中的数据网格?
基本上我想要实现的是:
,而不是(目前越来越)
我喜欢LinqPAD中.Dump()
扩展方法的可能性,并且希望用它来将Dictionary<string,string>
列表可视化为数据网格,其中键是列名,值分别是单个值。将字典列表可视化为LinqPAD中的数据网格?
基本上我想要实现的是:
,而不是(目前越来越)
您可以创建一个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();
你可以把他们变成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;
}
这是我能得到这么远,多亏了最好的结果。解决方案唯一的问题是,如果你使用'结果到DataGrid'选项,那么你不能得到数据网格,而是一组项目... –
如何只
listOfDictionaries.Select(d => new { One = d["one"], Two = d["two"] })
是的,我做了它产生的第一张照片,但我不每次我的密钥(例如我的表的列)改变时,都不想改变这种转换方法。 –
我找到了正确的方式来影响列名:根据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。
不幸的是,这并不为Results to Data Grids
模式,其中LINQPad(可能是由设计)只是忽略了ICustomMemberProvider
完全工作。
太棒了,这个伎俩!谢谢! –