2013-12-11 40 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完全工作。

相關問題