如何将字符串列表转换为双精度? [英] How to convert list of strings to doubles?

查看:1516
本文介绍了如何将字符串列表转换为双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我以前尝试过这两种方法 -

EDIT : I had tried these two ways before -



List<double> doubleList =
stringList.ConvertAll(x => (double)x);

List<double> doubleList =
stringList.Select(x =>
(double)x).ToList();

并收到此错误:


无法将类型'string'转换为'double'

Cannot convert type 'string' to'double'

我读了一些很熟悉,将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.

这篇关于如何将字符串列表转换为双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆