Reputation: 1902
I need to write an extension method with generic type T that goes through all properties of an object and does something to those that are dictionaries whose values are of type t:
public static T DoDictionaries<T,t>(T source, Func<t,t> cleanUpper)
{
Type objectType = typeof(T);
List<PropertyInfo> properties = objectType.GetProperties().ToList();
properties.Each(prop=>
{
if (typeof(Dictionary<????, t>).IsAssignableFrom(prop.PropertyType))
{
Dictionary<????, t> newDictionary = dictionary
.ToDictionary(kvp => kvp.Key, kvp => cleanUpper(dictionary[kvp.Key]));
prop.SetValue(source, newDictionary);
}
});
return source;
}
I cannot use another generic type ``k'' for type of dictionary keys since there can be many dictionaries with various key types in one object. Obviously, something different has to be done instead of the code above. I just can't figure out how to do this. Thanks
Upvotes: 0
Views: 942
Reputation: 4742
public static TSource DoDictionaries<TSource, TValue>(TSource source, Func<TValue, TValue> cleanUpper)
{
Type type = typeof(TSource);
PropertyInfo[] propertyInfos = type
.GetProperties()
.Where(info => info.PropertyType.IsGenericType &&
info.PropertyType.GetGenericTypeDefinition() == typeof (Dictionary<,>) &&
info.PropertyType.GetGenericArguments()[1] == typeof (TValue))
.ToArray();
foreach (var propertyInfo in propertyInfos)
{
var dict = (IDictionary)propertyInfo.GetValue(source, null);
var newDict = (IDictionary)Activator.CreateInstance(propertyInfo.PropertyType);
foreach (var key in dict.Keys)
{
newDict[key] = cleanUpper((TValue)dict[key]);
}
propertyInfo.SetValue(source, newDict, null);
}
return source;
}
Upvotes: 2