2016-05-17 104 views
0

如何轉換: 列表:創建從列表中的元素C#動態對象

var list = new List<string>(){"str1","str2"} 

一個匿名對象:

var anonymousObject = new {str1 = "str1",str2 = "str2"} 

運行

+0

你想通過這樣做是爲了解決什麼問題? – spender

+0

只需使用'Dictionary '。 – Rob

+0

我想要使用lambda表達式連接兩個數據表。 當我要加入單個列上它很容易和它看起來像這樣 Table1.Join(Table2, leftTable => leftTable["joincolumn"], rightTable => rightTable["joincolumn"], (leftTable,rightTable) => new {leftTable,rightTable} ) 但我有到位「joinColumn」的名單,這需要使用動態對象 new {column1=leftTable.column1,column2=leftTable.column2} 來處理,我的列表中有COLUMN1和第2列 – Nikhil

回答

0

可以使用ExpandoObject期間這會給你動態類型的功能。

 var list = new List<string>() { "str1", "str2" }; 
     ExpandoObject obj = new ExpandoObject(); 
     var store = (IDictionary<string, object>)obj; 

     list.ForEach(x => store.Add(x, x)); 

     dynamic lst = obj; 
     var val = lst.str1; // Test 
+0

謝謝,這是很好的信息 – Nikhil

+0

對不起,我說我的問題錯了,雖然 – Nikhil

0

您還可以使用下面表示的擴展方法(從here)。

因爲通過手動迭代項目將列表轉換爲動態對象可能會很痛苦,因爲在您的應用程序中存在許多像這樣的情況。

您可以使用此擴展方法是這樣的:

dynamic list = new List<string>() { "str1", "str2" } 
     .ToDictionary(dd => dd, dd => (object)dd) 
     .ToExpando(); 

擴展方法:

public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary) 
    { 
     var expando = new ExpandoObject(); 
     var expandoDic = (IDictionary<string, object>)expando; 

     // go through the items in the dictionary and copy over the key value pairs) 
     foreach (var kvp in dictionary) 
     { 
      // if the value can also be turned into an ExpandoObject, then do it! 
      if (kvp.Value is IDictionary<string, object>) 
      { 
       var expandoValue = ((IDictionary<string, object>)kvp.Value).ToExpando(); 
       expandoDic.Add(kvp.Key, expandoValue); 
      } 
      else if (kvp.Value is ICollection) 
      { 
       // iterate through the collection and convert any strin-object dictionaries 
       // along the way into expando objects 
       var itemList = new List<object>(); 
       foreach (var item in (ICollection)kvp.Value) 
       { 
        if (item is IDictionary<string, object>) 
        { 
         var expandoItem = ((IDictionary<string, object>)item).ToExpando(); 
         itemList.Add(expandoItem); 
        } 
        else 
        { 
         itemList.Add(item); 
        } 
       } 

       expandoDic.Add(kvp.Key, itemList); 
      } 
      else 
      { 
       expandoDic.Add(kvp); 
      } 
     } 

     return expando; 
    }