DataRow.Field
支持可为空的类型:
List<double> result = globalDS.Tables[0].AsEnumerable().AsParallel()
.Where(r => r.Field<double?>("PercentChange").HasValue)
.Select(r => r.Field<double?>("PercentChange").Value)
.ToList();
编辑:既然您提到该字段包含字符串而不是双精度数:
List<double> result = globalDS.Tables[0].AsEnumerable().AsParallel()
.Select(r => r.Field<string>("PercentChange").TryGetDouble())
.Where(nullDouble => nullDouble.HasValue)
.Select(nullDouble => nullDouble.Value)
.ToList();
我已经使用此扩展来尝试解析一个字符串,double?
该字符串比将“动态”解析为局部变量更安全,尤其是使用AsParallel
:
public static Double? TryGetDouble(this string item, IFormatProvider formatProvider = null)
{
if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
Double d = 0d;
bool success = Double.TryParse(item, NumberStyles.Any, formatProvider, out d);
if (success)
return d;
else
return null;
}