首页 新闻 会员 周边 捐助

C# 如何将匿名对象转为 Dictionary

0
悬赏园豆:30 [已解决问题] 解决于 2023-01-23 16:57

请问 C# 中如何将匿名对象(anonymous object)转换为字典(dictionary)?How to Convert anonymous object to dictionary in C#?

比如下面的匿名对象

var blogPost = new 
{ 
    Id = 1, 
    Title = "Understanding PathBase in ASP.NET Core"
};
问题补充:

还是 ExpandoObject 最方便,可以直接通过构造函数参数传给 Dictionary

dynamic blogPost = new ExpandoObject();
blogPost.Title = "C# Tip: Convert ExpandoObjects to IDictionary";
blogPost.Url = "https://www.code4it.dev/csharptips/expandoobject-to-dictionary";
var dict = new Dictionary<string, object>(blogPost);
Console.WriteLine(string.Join("\n", dict.Select(d => d.Key + ": " + d.Value)));
dudu的主页 dudu | 高人七级 | 园豆:30755
提问于:2023-01-23 10:11
< >
分享
最佳答案
0

匿名类型可以通过反射实现

var blogPost = new
{
    Id = 1,
    Title = "Understanding PathBase in ASP.NET Core"
};

IDictionary<string, string?> dict = blogPost
    .GetType()
    .GetProperties()
    .ToDictionary(p => p.Name, p => p.GetValue(blogPost)?.ToString());

Console.WriteLine(string.Join("\n", dict.Select(d => d.Key + ": " + d.Value)));
dudu | 高人七级 |园豆:30755 | 2023-01-23 16:56
dudu | 园豆:30755 (高人七级) | 2023-02-07 09:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册