2016-07-22 70 views
-3

我想轉換IEnumerable的,下面轉換IEnumerable的<Object>以匿名類型

public class NameVal 
    { 
     public string Name { get; set; } 
     public string Content { get; set; } 
    } 

    IEnumerable<NameVal> contents = new List<NameVal>() 
    { 
     new NameVal { Name = "title", Content = "My new post" }, 
     new NameVal { Name = "body", Content = "This is my first post!" } 
    }; 

定義爲匿名類型「數據」

 var data = new 
     { 
      title = "My new post", 
      body = "This is my first post!" 
     }; 

任何人都知道如何去嗎?謝謝。

+0

你可以使用字符串,字符串的字典? –

回答

0

我能想到的唯一的辦法是使用ExpandoObjectdynamic

var x = new ExpandoObject() as IDictionary<string, object>; 
foreach (NameVal nameVal in contents) { 
    x.Add(nameVal.Name, nameVal.Content); 
} 

dynamic d = x; 
Console.WriteLine(d.title); 
Console.WriteLine(d.body); 
+0

謝謝,這對我有用。 – pseudoware

0

很簡單。試試這個

var data = contents.Select(x => new 
     { 
      title = x.Name, 
      body = x.Content 
     }); 
+0

這會給出錯誤的輸出......你會得到2項而不是1,只有第二項的'body'屬性纔會有正確的值。 –