Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting text and converting linq

Tags:

c#

linq

I have a string array and want to convert it to double array with LINQ. I don't want to use foreach loops.

var texts = new List<string> 
{"-87.98 65", "-86.98 75", "-97.98 78", "-81.98 65"}

To:

var numerics = new List<IEnumerable<double>> 
{
     new List<double>{-87.98, 65},
     new List<double>{86.98, 75},
     new List<double>{-97.98 78},
     new List<double>{-81.98 65}
}

Is there any short way with LINQ?

like image 929
barteloma Avatar asked Jul 31 '15 11:07

barteloma


1 Answers

You could use this:

var doubles = texts.Select(x => x.Split()
                                 .Select(y => double.Parse(y, CultureInfo.InvariantCulture))
                                 .ToList()
                                 .AsEnumerable() // added to comply to the desired signature
                          )
                   .ToList() // added to comply to the desired signature
                   ;

It first selects the string, splits it on spaces, and then parses the strings in the string array to doubles. That output is converted to a list.

like image 136
Patrick Hofman Avatar answered Oct 29 '22 20:10

Patrick Hofman