King_Fisher
King_Fisher

Reputation: 1203

Cannot implicitly convert type 'System.Collections.Generic.List to class properties in C#

Model:

public class DataResult<T>
{
    public List<T> ViewResults;
}

public class oGateEntryViewModel 
{
    public DataResult<GateEntryModels> oListGateEntryModels { get; set; }
}

Controller:

GateEntryViewModel oGateEntryViewModel = new GateEntryViewModel();
IGateEntryBC oIGateEntryBC = new GateEntryBC();
oGateEntryViewModel.oListGateEntryModels = oIGateEntryBC.oGetGateEntryData();  --Error 
return View(oGateEntryViewModel);

oIGateEntryBC.oGetGateEntryData(); -> This method is returning the list Results.


public List<GateEntryModels> oGetGateEntryData()
{
    DataAdapters oDataAdapters = new DataAdapters();
    List<DataParameters> oListparams = new List<DataParameters>();
    DataParameters oDataparam;
    oDataparam = new DataParameters("@TYPE", SqlDbType.Int, (Int32)GateEntryEntities.EnumGateEntry.GateEntryList);
    oListparams.Add(oDataparam);
    DataTable dtList= oDataAdapters.GetData<DataTable>(oListparams, "PROC_GATEENTRY");

    return dtList.AsEnumerable().Select(i => new GateEntryModels()
    {
        GEID = int.Parse(i["GE_ID"].ToString()),
        GE_NO = i["GE_NO"].ToString(),
        TRANSPORTER = i["TRANSPORTER"].ToString()
    }).ToList();  
}

I'm trying to wrap multiple list results into a single models and bind the model in to view. When I tried to assign the list value into oListGateEntryModels property, its throwing an error. How do I fix this?

Error:

Cannot implicitly convert type 'System.Collections.Generic.List<TS.Models.GateEntryModels>' to 'TS.Models.DataResult<TS.Models.GateEntryModels>'

Upvotes: 0

Views: 1585

Answers (2)

D Stanley
D Stanley

Reputation: 152556

You're trying to "convert" a list to a type that contains a list, which is not directly possible.

The easiest solution would be to assign the property instead:

oGateEntryViewModel.oListGateEntryModels.ViewResults = oIGateEntryBC.oGetGateEntryData(); 

or

oGateEntryViewModel.oListGateEntryModels = new DataResult<GateEntryModels>
    {
        ViewResults = oIGateEntryBC.oGetGateEntryData()
    };

if you need to initialize the oListGateEntryModels property first.

Upvotes: 1

DCruz22
DCruz22

Reputation: 806

You have to make the conversion explicitly, try this to convert:

List<GateEntryModels> listName = dtList.AsEnumerable().Select(i => new MyType()
{
   GEID = i.Field<string>("GE_ID"),
   GE_NO = i.Field<string>("GE_NO"),
   TRANSPORTER = i.Field<double>("TRANSPORTER ")
}).ToList();

return listName;

Upvotes: 0

Related Questions