2013-12-11 39 views

回答

4

您可以创建一个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(); 
+0

太棒了,这个伎俩!谢谢! –

5

你可以把他们变成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"

+0

这是我能得到这么远,多亏了最好的结果。解决方案唯一的问题是,如果你使用'结果到DataGrid'选项,那么你不能得到数据网格,而是一组项目... –

2

如何只

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

是的,我做了它产生的第一张照片,但我不每次我的密钥(例如我的表的列)改变时,都不想改变这种转换方法。 –

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

不幸的是,这并不为Results to Data Grids模式,其中LINQPad(可能是由设计)只是忽略了ICustomMemberProvider完全工作。

相关问题