Plumbum7
Plumbum7

Reputation: 109

foreach array keeps overwritten (beginner)

The next peace of code,

foreach (var trksegg in trk.Segs)
        { 
        double lon = Convert.ToDouble(trksegg.Longitude);
        double lat = Convert.ToDouble(trksegg.Latitude);
        double[,] lonlat = { { lon, lat } };

Looks like to keeps overwriting my lonlat array, so the array never gets bigger the [0,0] lon value and [0,1] lat value.

This probably is a beginners question(i'm beginner and cannot figure it out), but how can i fill the array with multiple valua's. Thank you in advance.

Upvotes: 2

Views: 643

Answers (3)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

The lonlat variable is local to your foreach loop: the array it contains gets recreated in each iteration.

Arrays in C# cannot be grown. You could preallocate the array, as @Mikant does, or you could accumulate the results in a List<T>, or you could use LINQ:

var lonlats = trk.Segs.Select(
    trksegg => new[] {
        Convert.ToDouble(trksegg.Longitude),
        Convert.ToDouble(trksegg.Latitude)
    }).ToArray();

Upvotes: 0

Mikant
Mikant

Reputation: 326

just put the array declaration outside the loop

double[,] lonlat = new double[trk.Segs.Length, 2];
for (int i=0; i<trk.Segs.Length; i++) {
    lonlat[i,0] = Convert.ToDouble(trk.Segs[i].Longitude);
    lonlat[i,1] = Convert.ToDouble(trk.Segs[i].Latitude);
}

there is also one little mistake: an array doesn't have an Add method, it supports only indexed access, so if you write

arr = { { lon, lat } }

in a loop, it will always reassign new array to your var, so it also makes no sense. in my example lon and lat are added via indexes

Upvotes: 6

Tony The Lion
Tony The Lion

Reputation: 63200

You have declared the array inside your foreach loop, so it will create a new one each iteration of the loop. You should declare it outside the loop and use it inside, then you'll get what you want.

So:

double[,] lonlat;

foreach(var trsksegg in trk.Segs)
{
    lonlat = { { lon, lat } };
}

Upvotes: 0

Related Questions