user4664405
user4664405

Reputation:

Add elements to a sublist of a list in C#

I don't know if this question is too easy but I haven't found anything at the internet to solve this problem.

I have a List of Lists where I add three sublists.

 List<List<DateTime>> myList= new List<List<DateTime>>();

 while (countNeededSubLists != 0)
 {
   myList.Add(new List<DateTime>());
   countNeededSubLists--;
 }

Now I want to simply add a new Date to the sublist which is at index 1 of my list. How to achieve that and what is the correct syntax for that?

Thanks in advance.

Upvotes: 1

Views: 1702

Answers (2)

Pedro Benevides
Pedro Benevides

Reputation: 1974

I recommend you to always check if it is not null, like this:

if(!myList.Any())
    return;

myList.[1].Add(new DateTime());

Upvotes: 0

adv12
adv12

Reputation: 8551

myList[1].Add(new DateTime());

Upvotes: 3

Related Questions