转换IEnumerable<;对象>;到匿名类型

本文关键字:类型 对象 IEnumerable lt 转换 gt | 更新日期: 2023-09-27 17:58:14

我想转换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!"
};

有人知道怎么做吗?谢谢

转换IEnumerable<;对象>;到匿名类型

我能想到的唯一方法是使用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);

非常简单。试试这个

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