问题描述
编辑:我以前尝试过这两种方法 -
List<double> doubleList =
stringList.ConvertAll(x => (double)x);
List<double> doubleList =
stringList.Select(x =>
(double)x).ToList();
并收到此错误:
我读了一些,将int转换为双精度...但是我有需要转换为双精度列表的字符串列表ConvertAll()不适用于Select扩展方法。任何人都可以帮助我。
I read about something similiar that convert ints to doubles...but I have List of strings which I need to convert to List of doubles and the ConvertAll() does not work neither the Select extension method. Can anyone please help me out.
推荐答案
如果您使用的是.NET 3.5或更新版本,则select方法应该可以工作: p>
The select method ought to work if you are using .NET 3.5 or newer:
List<double> result = l.Select(x => double.Parse(x)).ToList();
以下是一些示例代码:
List<string> l = new List<string> { (0.1).ToString(), (1.5).ToString() };
List<double> result = l.Select(x => double.Parse(x)).ToList();
foreach (double x in result)
{
Console.WriteLine(x);
}
结果:
0,1
1,5
有一件事要注意的是哪种文化你正在使用来解析字符串。您可能希望使用 Parse
重载文化,并使用 CultureInfo.InvariantCulture
。
One thing to be aware of is which culture you are using to parse the strings. You might want to use the Parse
overload that takes a culture and use CultureInfo.InvariantCulture
for example.
这篇关于如何将字符串列表转换为双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!