Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - How to convert list of strings to doubles?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...