我刚刚花了大约 20 分钟试图找出是否有一种简洁的/LINQy 方式来填充这个字典:
private Dictionary<string, List<Type>> _propertyMap;
它旨在成为一个字典,从有限的类型列表中将公共(public)属性的名称映射到具有此类属性的类型。
我敢肯定一定有一种聪明的方法来获取类型列表,并将其扩展为成对的 {Type, PropertyInfo}并从那里构建这本字典,但我就是无法理解它。
这是我填充这本词典的当前方式。 ( _types 是一个 List<Type> ):
_propertyMap = new Dictionary<string, List<Type>>();
foreach (var t in _types)
{
foreach (var p in t.GetProperties(
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance))
{
if (_propertyMap.ContainsKey(p.Name))
{
_propertyMap[p.Name].Add(t);
}
else
{
_propertyMap[p.Name] = new List<Type> {t};
}
}
}
请您参考如下方法:
您可以使用 LINQ 查询:
var flags = BindingFlags.Public | BindingFlags.Instance;
_propertyMap = _types.SelectMany(t => t.GetProperties(flags))
.GroupBy(p => p.Name)
.ToDictionary(g => g.Key,
g => g.Select(p => p.DeclaringType).ToList());
旁注 - 您可以使用 ILookup<string, Type>而不是 Dictionary<string, List<Type>>那么查询将是这样的:
_propertyMap = _types.SelectMany(t => t.GetProperties(flags))
.ToLookup(p => p.Name, p => p.DeclaringType);
