tilenslo
tilenslo

Reputation: 103

List with string array (List<string[]>)

I have some strange problem where all my string arrays has the same value in the List. Here is my code:

List<string[]> map_data = new List<string[]>();
string[] map_data_array = new string[11];

for(int i = 0; i < 2000; i++)
{
    map_data_array = PopulateDataFromFile(); // it returns different data every call
    map_data.Add(map_data_array); // store to List
}

map_data_array has always different data, I've verified that by placing the break point there and I've checked it.

The problem is that map_data has the value of all elements the same. And this value is the data that comes from function PopulateDataFromFile when the i is 1999.

What I am doing wrong? :/

Upvotes: 9

Views: 68753

Answers (4)

DGibbs
DGibbs

Reputation: 14618

You need to process your data in chunks since PopulateDataFromFile(); looks to be returning all of its data in one go (or as much as the array can fit). Using an extension method, you could do something like this: -

List<string[]> map_data = new List<string[]>();
foreach (var batch in PopulateDataFromFile().Batch(11))
{
       map_data.Add((batch.ToArray());
}

Extension method: -

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int batchSize)
{
     return items.Select((item, inx) => new { item, inx })
                 .GroupBy(x => x.inx / batchSize)
                 .Select(g => g.Select(x => x.item));
}

Upvotes: 1

hakish
hakish

Reputation: 4048

PopulateDataFromFile() is returning a String array with the same values.

Upvotes: 0

srsyogesh
srsyogesh

Reputation: 609

In the loop everytime you just change the address of map_data_array , so that's why always the value will get changed to the newer data obtained from the method call. Reinitialize the string array everytime will help. It should look something like this

    for(int i = 0; i < 2000; i++)
    {
         string[] map_data_array = PopulateDataFromFile(); // it returns different data every call
         map_data.Add(map_data_array); // store to List
    } 

or if its confusing for you can you make it simple by

    for(int i = 0; i < 2000; i++)
    {             
         map_data.Add(PopulateDataFromFile()); // store to List
    } 

Upvotes: -5

nvoigt
nvoigt

Reputation: 77304

That only happens if you place the same array into the list. As you did not give the code to PopulateDataFromFile we can only guess what happens. Make sure that the function returns a seperate array created with new each time.

Upvotes: 12

Related Questions