如何将字符串转换为双打的名单? [英] How to convert list of strings to doubles?

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

问题描述


编辑:我曾尝试过这两种方式 -




 列表与LT;双> doubleList = 
stringList.ConvertAll(X =>(双)x)的;

名单,LT;双> doubleList =
stringList.Select(X =>
(双)X).ToList();

和得到这个错误:




无法转换类型'字符串'to'double




我读到的东西的similiar ......但我有列表和在ConvertAll()不工作,无论是选择扩展方法。 。任何人都可以请帮我


解决方案

select方法应该如果您正在使用.NET 3.5或更高版本的工作:

 列表<双>结果= l.Select(X => double.Parse(X))。了ToList(); 

下面是一些示例代码:

 列表<串GT; L =新的List<串GT; {(0.1)的ToString(),(1.5)的ToString()}; 
名单,LT;双>结果= l.Select(X => double.Parse(X))。了ToList();
的foreach(在结果双X)
{
Console.WriteLine(x)的;
}



结果:

 
0,1
1,5

有一点需要注意的是,你的文化使用解析字符串。您可能需要使用解析重载需要一个文化和使用 CultureInfo.InvariantCulture 例如


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();

and got this error:

Cannot convert type 'string' to'double'

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.

解决方案

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();

Here is some example code:

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);
}

Result:

0,1
1,5

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天全站免登陆