Reputation: 9
`Please am new-bee to programming and also have searched for the last few hours on a solution but cant find one; So here is my problem:
I have a List<KeyValuePair<string, object>>
I want to convert the value pair at run-time to a ICollection<T>
Where T is the Type of object (The Value pair).
The purpose of the conversion is to pass the values into the PropertyInfo.SetValue(obj, val) method. Where val is the ICollection
public object TheMEthod( object objreactor, List<KeyValuePair<string, object>> objactor) {
Type tyr2 = typeof(List<>).MakeGenericType(objactor.First().Value.GetType());
ICollection list = (ICollection) Activator.CreateInstance(tyr2);
list = (ICollection) objactor.Select(l => l.Value).Distinct().ToList();
objreactor.GetType().GetProperty(objactor.First().Key)?.SetValue(objreactor, Convert.ChangeType( list, objactor.First().Value.GetType()), null);
//else return exception
return objreactor;
}
This returns the error object must implement iconvertible c#"
Upvotes: 0
Views: 404
Reputation: 136174
If the keyvalue pair has an object
as the value, but you need it to be a specific object T
you'll need to cast it. This will only work if the Value
really is the right type.
List<KeyValuePair<string, object>> list = ....
ICollection<TheRealObject> coll = list.Select(x => x.Value) // Select the Values
.Cast<TheRealObject>() //Cast them to your type
.ToList(); // turn it to a list
Note that List<T>
is a ICollection<T>
so you can almost certainly pass this list to a SetProperty
expecting an ICollection<T>
Upvotes: 2