Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert from object to model type

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();
like image 959
DaGrooveNL Avatar asked May 10 '26 04:05

DaGrooveNL


2 Answers

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.

like image 52
xlecoustillier Avatar answered May 11 '26 18:05

xlecoustillier


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();
like image 20
Panagiotis Kanavos Avatar answered May 11 '26 16:05

Panagiotis Kanavos