0

I have a list of seven dates, one for each day of a given week, each date is meant to have a list of events that happened on that day, there can be no events on a day. dates is an array of 7 DateTime days. My code to do this is as follows:

 var dateData = new List<List<Timelineinfo>>(new List<Timelineinfo>[7]);           
       for (int i = 0; i < 7; i++)
       {            
         dateData[i].AddRange(_context.Timelineinfo
                              .Where(t => t.Date.Equals(dates[i].ToString("yyyy-MM-dd")))
                              .ToList());
       }    

However, I am getting and error of:

Object reference not set to an instance of an object. on dateData[i]

Bubinga
  • 511
  • 1
  • 14

2 Answers2

2

new List<Timelineinfo>[7] creates an 7-element array of List<Timelineinfo> objects that does not contain any values. It is equivalent to the following expression:

new List<Timelineinfo>[]
{
    null,
    null,
    null,
    null,
    null,
    null,
    null,
}

So this creates an array for that type with 7 elements but the values of each array element is not yet initialized. So you only allocate for the room but there is no value.

Passing this array to the constructor new List<List<Timelineinfo>>(array) does nothing than copying those uninitialized array elements over into the new list that is being created. So the list will then also contian uninitialized list elements.

In order to be able to use these elements, you will have to initialize them first. Since you already loop over the items, you can do it in the loop body:

var dateData = new List<List<Timelineinfo>>(new List<Timelineinfo>[7]);
for (int i = 0; i < 7; i++)
{
    dateData[i] = new List<Timelineinfo>();

    dateData[i].AddRange(_context.Timelineinfo
        .Where(t => t.Date.Equals(dates[i].ToString("yyyy-MM-dd")))
        .ToList());
}

In your particular situation, you would be creating a list and then add to that list elements of another list directly, so you could also just assign that list to the list element directly:

for (int i = 0; i < 7; i++)
{
    dateData[i] = _context.Timelineinfo
        .Where(t => t.Date.Equals(dates[i].ToString("yyyy-MM-dd")))
        .ToList();
}
poke
  • 307,619
  • 61
  • 472
  • 533
0

You need to add dateData[i] = new List<Timelineinfo>(); before the linq.

vivek nuna
  • 12,695
  • 7
  • 48
  • 123