我有一个包含天气预报数据的XML文件。我正在尝试通过XDocument查询它。我有一个名为“Forecast”的类,我正在尝试创建此类型的对象,并使用LINQ填充其属性,如下所示:
public Forecast CurrentConditions(string stateName, string cityName)
{
var data = from i in weatherResponse.Descendants("current_observation")
select new Forecast
{
TemperatureC = Convert.ToDouble(i.Element("temp_c").Value)
//Setting other properties here
};
return data;
}
我的“Forecast”类只包含以下属性:
class Forecast
{
public double TemperatureF { get; set; }
public double TemperatureC { get; set; }
public string RelativeHumidity { get; set; }
}
然而,VS强调了return data;
并且说 "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<WeatherUnderground1.Forecast>' to 'WeatherUnderground1.Forecast'. An explicit conversion exists (are you missing a cast?)"
所以如果我更改为:
return (Forecast)data;
我得到了异常信息“Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.”。
问题:
我做错了什么?返回Forecast对象的正确方式是什么?
return data.FirstOrDefault()
- L.BTemperatureC = (double)i.Element("temp_c")
- Chuck Savage