Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to split this string using LINQ?

Tags:

c#

linq

I've got some longitude\latitude coordinates bunched together in a string that I'd like to split into longitude\latitude pairs. Thanks to stackoverflow I've been able to come up with the some linq that will split it into a multidimensional string array. Is there a way to split the string directly into an object that accepts the longitude latitude vs a string array then create the object?

string segment = "51.54398, -0.27585;51.55175, -0.29631;51.56233, -0.30369;51.57035, -0.30856;51.58157, -0.31672;51.59233, -0.3354"

string[][] array = segment.Split(';').Select(s => s.Split(',')).ToArray();
foreach (string[] pair in array)
{
//create object here
}
like image 603
NullReference Avatar asked Apr 09 '12 21:04

NullReference


People also ask

What function can be used to split the string?

The split() method splits a string into an array of substrings. The split() method returns the new array.

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

How do you split a string into values?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

Which method can you use character other than comma to separate values from array?

We can call the split() method on the message string. Let's split the string based on the space ( ' ' ) character.


2 Answers

Some tasks are just easier to solve the old way:

var split = segment.Split();
var coordinates = new List<Coordinate>(split.Length);
foreach(string s in split)
{
    coordinates.Add(new Coordinate(s));
}
like image 88
GSoft Consulting Avatar answered Sep 30 '22 18:09

GSoft Consulting


You are close. Something like this might help:

var pairSequence = segment.Split(';')
        .Select(s => s.Split(','))
        .Select(a => new { Lat = double.Parse(a[0]), Long = double.Parse(a[1]) });
like image 39
mmx Avatar answered Sep 30 '22 19:09

mmx