将IEnumerable <object>转换为匿名类型

时间:2016-07-22 08:24:36

标签: c# linq anonymous-types

我想转换IEnumerable,定义如下:

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!" }
};

匿名类型data

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

有谁知道如何解决这个问题?感谢。

2 个答案:

答案 0 :(得分:0)

很简单。试试这个

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

答案 1 :(得分: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);