Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? :/

like image 667
tilenslo Avatar asked Jun 18 '13 10:06

tilenslo


2 Answers

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.

like image 198
nvoigt Avatar answered Oct 12 '22 17:10

nvoigt


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));
}
like image 33
DGibbs Avatar answered Oct 12 '22 17:10

DGibbs