在列表<dynamic>中添加动态项

时间:2017-01-31 06:30:07

标签: c# list

List<dynamic> homePageDataList = new List<dynamic>();        
DataTable dt = GetData();        
  homePageDataList.Add(new
{
    Vehicle = dt.Rows[0]["vehName"],
    Lati = dt.Rows[0]["lat"],
    Long = dt.Rows[0]["lngt"],


    if(dt.Rows[0]["userType"].ToString()=="2")
    {
        TripStatus =  dt.Rows[0]["delstatus"].ToString();                                        
    }                                
     Date = dt.Rows[0]["dtTime"],
});  

我只想在TripStats的条件下添加userType==2

2 个答案:

答案 0 :(得分:3)

如果要动态添加属性,请考虑使用expando对象。

List<dynamic> homePageDataList = new List<dynamic>();        
DataTable dt = GetData();  

dynamic expando = new ExpandoObject();
            expando.Vehicle = dt.Rows[0]["vehName"];
            expando.Lati =dt.Rows[0]["Lati "];
            expando.Long = dt.Rows[0]["Long "];
            expando.Date = dt.Rows[0]["Date "];

 if(dt.Rows[0]["userType"].ToString()=="2")
    {
        expando.TripStatus =  dt.Rows[0]["delstatus"].ToString();                                        
    }    

homePageDataList.Add(expando);

答案 1 :(得分:2)

您可以使用Ternary Operator(内联if语句),如下所示:

TripStatus = dt.Rows[0]["userType"].ToString()=="2" ? dt.Rows[0]["delstatus"].ToString() : "",