Home > database >  How to write a for loop in LINQ
How to write a for loop in LINQ

Time:02-17

one question bothers me. I'm reading a file that has coordinates(longitude and latitude).

The contents of the file: 50.29264389999999,18.91857099999993;50.0347499,21.967057000000068;54.4547473,17.042384500000026;

I made a class for the coordinates

internal class Coordinate
    {
        public double Longitude { get; set; }
        public double Latitude { get; set; }
        public Coordinate(double longitude,double latitude)
        {
            this.Longitude = longitude;
            this.Latitude = latitude;
        }
    }

And I use this code to read the file and list them.

List<Coordinate> cordinates = new List<Coordinate>();
var items = File.ReadAllText("../../../Files/input-01.txt").Split(new char[] { ',', ';' }).Select(double.Parse).ToList();
for(int i = 0; i < items.Count; i =2)
{
    cordinates.Add(new Coordinate(items[i], items[i   1]));
}            

The program works, but is there a way to write this for loop in LINQ ?

CodePudding user response:

Ok let's try to pick each coordinate once

File.ReadAllText(filepath).Split(';')

To clarify your code add a new function to your coordinate class as this

public Coordinatex(string[] s){this.Longitude = double.Parse(s.First());this.Latitude = double.Parse(s.Last());}

Then put all items as coordinate objets by splitting and casting to double, so the result maybe looks like this

File.ReadAllText(filepath).Split(';').Select(x => new Coordinatex(x.Split(',')));

Hope this works to you

  • Related