Capn Jack Capn Jack - 1 month ago 5
C# Question

How to dynamically add lists to a list? And then add items to that newly added list in the list of lists?

This is going to be hard to communicate so bare with me here...

Say I have a list of fruits organised in a list. The list is organized so that firstly the word 'person' will appear on the list and all proceeding items after that person are fruit that belong in their basket. Then the next person listed marks a parse moment to start a new list of fruits for a new person. Finally I want all these lists of fruits for all these people to be compiled into a list of lists. The number of fruits and number of people are unknown. However the types of fruits that can appear are known.

Here's an example list if the above doesn't make sense:

Person
Apple
Apple
Cherry
Apple
Orange
Person
Grape
Lemon
Apple
Apple


Only available fruits: Apple, Cherry, Orange, Grape, Lemon

Here's my attempt at the code, I used comments where I think list adding should occur but I'm not sure what the syntax should be (thats what I'm asking for help with):

while (notAtEndOfList)
{
//create a new list of fruit for a person
while (notAtEndOfList && input != "person")
{
nameOfDynamicallyCreatedFruitList.add(input.ToString());
}
peopleWithFruitList.add(nameOfDynamicallyCreatedFruitList);
}


EDIT: if anyone has a better title for this let me know thanks

Answer

I would recommend using the following data structure to represent your data:

Dictionary<String, List<String>> MyData = new Dictionary<String, List<String>>();
Comments