I have an empty list with models of type 'audi_b9_aismura' which I want to populate with an object which I retrieve from another list.
I know this object is of the type specified (audi_b9_aismura) but I cannot add it to the list, using Convert.Changetype does not work either. The code below throws (at design time) the following error: Cannot convert from 'object' to '.audi_B9_aismura'.
List<audi_b9_aismura> dataList = new List<audi_b9_aismura>();
if (obj.GetType().Equals(typeof(audi_b9_aismura)))
{
dataList.Add(Convert.ChangeType(obj, typeof(audi_b9_aismura)));
}
I also tried, which does not work either.
audi_b9_aismura testVar = Convert.ChangeType(obj, typeof(audi_b9_aismura));
And, which converts it ok, but when adding it says again it is of the type object.
var testVar = Convert.ChangeType(obj, typeof(audi_b9_aismura));
dataList.Add(testVar);
If I retrieve the object type by filling it in a string, it returns the correct type (audi_b9_aismura)
string result = Convert.ChangeType(obj, typeof(audi_b9_aismura)).GetType().ToString();
Why not do a simple cast :
if (obj is audi_b9_aismura)
{
dataList.Add((audi_b9_aismura)obj);
}
As Ben Robinson said in his comment, Convert.ChangeType() returns an object that still has to be cast to the right type.
LINQ provides the Cast<> and OfType<> methods that allow you to cast or filter object by a speficic type respectively.
To retrieve items of a specific type as a list you can write:
var dataList=sourceList.OfType<audi_b9_aismura>().ToList();
If you are sure that the source contains only items of the specific type, you can write:
var dataList=sourceList.Cast<audi_b9_aismura>().ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With