c# convert from object to model type

26.4k Views Asked by At

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();
3

There are 3 best solutions below

4
On BEST ANSWER

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.

0
On

Try:

List<audi_b9_aismura> dataList = new List<audi_b9_aismura>();

if (obj is audi_b9_aismura)
{
    dataList.Add((audi_b9_aismura)obj);
}
0
On

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();