【发布时间】:2019-07-15 12:13:17
【问题描述】:
我正在寻找一种方法将包含动态对象的List<object> 转换为字典,其中键是属性名,值是该属性的不同值。
目前我使用了这段代码,但我觉得必须有更优雅/更快的方法来做到这一点?
var records = ((IEnumerable)enumerable).Cast<object>().ToList();
var result = new Dictionary<string, IList<string>>();
foreach (object record in records)
{
foreach (var propertyName in properties)
{
var colValue = record.GetType().GetProperty(propertyName).GetValue(record, null);
if (colValue != null)
{
if (result.ContainsKey(propertyName))
{
result[propertyName].Add(colValue.ToString());
}
else
{
result.Add(propertyName, new List<string>() { colValue.ToString() });
}
}
}
}
【问题讨论】:
标签: c# .net linq dictionary