Search code examples
c#jagged-arrays

Jagged Array is always empty


I can't seem to figure out why item within a List is not being appended to a Jagged Array.

I have the following code

var list = new List<(double,double)>{                
          ( -99.8299313, 32.2840118),
          ( -99.8293304, 32.2840118),
};

var jaggedArray = new double[list.Count()][];
foreach (var item in list)
{
   var s = item.Split(",");
   jaggedArray.Append(new string[] { 
              Convert.ToDouble(s[0]), 
              Convert.ToDouble(s[1]) })
                     .ToArray();
}    

When I inspect the array it's empty? What am I doing wrong?

I have even declared the size of the array using list.Count() but its always empty?


Solution

  • From Enumerable.Append docs:

    This method does not modify the elements of the collection. Instead, it creates a copy of the collection with the new element.

    Which is demonstrated by the code sample there:

    // Creating a list of numbers
    List<int> numbers = new List<int> { 1, 2, 3, 4 };
    
    // Trying to append any value of the same type
    numbers.Append(5);
    
    // It doesn't work because the original list has not been changed
    Console.WriteLine(string.Join(", ", numbers));
    
    // It works now because we are using a changed copy of the original list
    Console.WriteLine(string.Join(", ", numbers.Append(5)));
    
    // If you prefer, you can create a new list explicitly
    List<int> newNumbers = numbers.Append(5).ToList();
    
    // And then write to the console output
    Console.WriteLine(string.Join(", ", newNumbers));
    
    // This code produces the following output:
    //
    // 1, 2, 3, 4
    // 1, 2, 3, 4, 5
    // 1, 2, 3, 4, 5
    

    So one thing you can do is reassign the jaggedArray (after fixing the issue I've mentioned in the comment):

    jaggedArray = jaggedArray.Append(new string[] { s[0], s[1] }).ToArray();
    

    Though it would not be the most effective approach. A better one would be to just go with LINQ all the way:

    List<string> list = ...;
    
    var jaggedArray = list
        .Select(s => s.Split(","))
        .Select(s => new string[] { s[0], s[1] }) 
        .ToArray();
    

    Note that new string[] { s[0], s[1] } will throw if there is less than 2 elements, consider using Where(s => s.Length > 1) to filter out such cases if appropriate.