Robert Smith
Robert Smith

Reputation: 13

How to convert a list to a jagged array in c#?

I am calling a third party API that expect a jagged array as input but I need to build this list dynamically.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var slots = new DateTime[][]
                {
                    new DateTime[] {new DateTime(2020, 2, 14), new DateTime(2020, 2, 20)},
                    new DateTime[] {new DateTime(2020, 2, 15), new DateTime(2020, 2, 23)},
                    new DateTime[] {new DateTime(2020, 2, 16), new DateTime(2020, 2, 24)}
                };

                DateTime[][] slots2;
                List<DateTime> appointments=new List<DateTime>();
                appointments.Add(new DateTime(2020, 2, 14));
                appointments.Add(new DateTime(2020, 2, 20));
                slots2 = appointments.ToArray();
            }
        }

}

in the above code when I try to initialize the jagged array slots with datetime objects it works fine but when I try to use appointments list I get an error with slots2. How to initialize slot2 with a list of date time to populate slots2?

Upvotes: 0

Views: 266

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

You need to initialise it first.

// create 1 element in the first dimension
var slots2 = new DateTime[1][];

var appointments = new List<DateTime>
                              {
                                 new DateTime(2020, 2, 14),
                                 new DateTime(2020, 2, 20)
                              };

// add the second dimension to the first element you created
slots2[0] = appointments.ToArray();

or

var slots2 = new[]
            {
               new[]
               {
                  new DateTime(2020, 2, 14),
                  new DateTime(2020, 2, 20)
               }
            };

Edit

Why not just use List<List<DateTime>> and project them into arrays

var appointments = new List<List<DateTime>>
                   {
                      new List<DateTime>
                      {
                         new DateTime(2020, 2, 14),
                         new DateTime(2020, 2, 20)
                      }
                   };

Then you can add more

 appointments.Add(new List<DateTime>
    {
       new DateTime(2020, 2, 14),
       new DateTime(2020, 2, 20)
    });

var slots2 = appointments.Select(x => x.ToArray()).ToArray();

Upvotes: 1

Related Questions