c# convert from object to model type

18,724

Solution 1

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.

Solution 2

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

Solution 3

Try:

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

if (obj is audi_b9_aismura)
{
    dataList.Add((audi_b9_aismura)obj);
}
Share:
18,724
DaGrooveNL
Author by

DaGrooveNL

Updated on June 04, 2022

Comments

  • DaGrooveNL
    DaGrooveNL almost 2 years

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