To pass null values to float data type to add it into list

徘徊边缘 提交于 2019-12-11 20:23:43

问题


I am trying to pass the null value to float data type as follow,

float? period_final_value = null; 

and getting the value in period_final_value from the parsing xml string as follows

var action = xmlAttributeCollection_for_period["value"];
xmlActionsone[j] = action.Value;
period_final_value = float.Parse(action.Value); 

and then adding this obtained value to list as follows

serie_line.data.Add(period_final_value);

Defined my list as follows

var serie_line = new { name = series_name, data = new List<float?>() };

Now, My issue is when I am trying to pass value,it shold get add to the list, and moment when no value is recognized then it should add null has the value in the place of empty value in list but I don't know I am not able to get it work properly...my web service crashes moment it counters any blank value...any help will be greatly appreciated...

plz note...the var serie_line..I am going to serialize it into JSON format so that I can use those values to plot chart.


回答1:


It sounds like you might be looking for TryParse instead of Parse.

When you call period_final_value = float.Parse(action.Value);, Parse will either parse the string into a float or throw an exception. It will never return null.

To get the behavior you want, try something like this:

float temp_value = 0;
float? period_final_value = null;
if (float.TryParse(action.Value, out temp_value)) {
    period_final_value = temp_value;
}

serie_line.data.Add(period_final_value);

If action.Value is a string representation of a number, then period_final_value will be that number. Otherwise, it will be null. You can then add it to your list of float? values.




回答2:


At this line

float? period_final_value = float.Parse(action.Value); 

you are loosing the nullable float. When it fails to parse (there is no value or the value is not a valid float), it throws instead of returning null. period_final_value will never have null as a value.

See gleng's answer to be able to set null to period_final_value.



来源:https://stackoverflow.com/questions/20424730/to-pass-null-values-to-float-data-type-to-add-it-into-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!