请问 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)));
匿名类型可以通过反射实现
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)));
相关博问:如何对dynamic中的一个属性进行修改