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

I have longitude / latitude coordinates grouped together into a string that I would like to split into longitude / latitude pairs. Thanks to stackoverflow, I was able to come up with some linq that will split it into a multidimensional array of strings. Is there a way to split a string directly into an object that takes a latitude longitude and a string array, and then create an 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 } 
+9
c # linq
source share
7 answers

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]) }); 
+23
source share

Assuming you have a Coordinate class with a public Coordinate(double x, double y) constructor, you can do this:

 Coordinate[] result = segment .Split(';') .Select(s => s.Split(',')) .Select(a => new Coordinate(x: double.Parse(a[0], NumberStyles.Number), y: double.Parse(a[1], NumberStyles.Number)) .ToArray(); 

or equal

 var query = from item in segment.Split(';') let parts = item.Split(',') let x = double.Parse(parts[0], NumberStyles.Number) let y = double.Parse(parts[1], NumberStyles.Number) select new Coordinate(x, y); Coordinate[] result = query.ToArray(); 
+6
source share

You can do it:

 public class GeoCoordinates { public decimal Latitude { get; set; } public decimal Longitude { get; set; } public GeoCoordinates( string latLongPair ) { decimal lat, lng; var parts = latLongPair.Split( new[] { ',' } ); if( decimal.TryParse( parts[0], out lat ) && decimal.TryParse( parts[1], out lng ) ) { Latitude = lat; Longitude = lng; } else { // you could set some kind of "ParseFailed" or "Invalid" property here } } } 

Then you can create a collection of GeoCoordinate classes as follows:

 var coords = segment.Split( new[] {';'} ).Select( x => new GeoCoordinates( x ) ); 
+3
source share

Here are some nice snippets:

  • precompiled regexen
  • LINQ to anonymous type projection
  • Parsing and printing culture-supporting numbers ( correct )

You want to extract certain code (for example, parsing numbers) in real life.

Watch live on Ideone.com

 using System; using System.Linq; using System.Text.RegularExpressions; using System.Globalization; namespace SODemo { class MainClass { private static readonly CultureInfo CInfo = CultureInfo.CreateSpecificCulture("en-US"); public static void Main (string[] args) { 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"; var re = new Regex(@"\s*(?<lat>[-+]?[0-9.]+),\s*(?<lon>[-+]?[0-9.]+)\s*;", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); var locations = re.Matches(segment).Cast<Match>().Select(m => new { Lat = decimal.Parse(m.Groups["lat"].Value, CInfo), Long = decimal.Parse(m.Groups["lon"].Value, CInfo), }); foreach (var l in locations) Console.WriteLine(l); } } } 

Output:

 { Lat = 51,54398, Long = -0,27585 } { Lat = 51,55175, Long = -0,29631 } { Lat = 51,56233, Long = -0,30369 } { Lat = 51,57035, Long = -0,30856 } { Lat = 51,58157, Long = -0,31672 } 
+3
source share

Do I need to use LINQ? You can do this with the standard line splitting function:

 string[] pairsOfCoords = segment.Split(';'); List<CoordsObject> listOfCoords = new List<CoordsObject>(); foreach (string str in pairsOfCoords) { string[] coords = str.Split(','); CoordsObject obj = new CoordsObject(coords[0], coords[1]); listOfCoords.Add(obj); } 
+2
source share

I could add a little more. Thanks to dtb for starters, upvoted. If you disable the parsing function, you can more cleanly handle error conditions, for example, the wrong number of elements in your array or things that are not analyzed with a decimal point.

 Coordinate[] result = segment .Split(';') .Select(s => s.Split(',')) .Select(BuildCoordinate) .ToArray(); Coordrinate BuildCoordinate(string[] coords) { if(coords.Length != 2) return null; return new Coordinate(double.Parse(a[0].Trim(), double.Parse(a[1]); } 
+1
source share

Some tasks are simply easier to solve the old fashioned way:

 var coordinates = new List<Coordinate>(); foreach(string s in segment.Split()) { coordinates.Add(new Coordinate(s)); } 
0
source share

All Articles