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

You could do this:

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 thusly:

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

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

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 equally

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

Tags:

C#

Linq