如何动态地将列表添加到列表中,然后将项目添加到列表列表中的新添加列表中?

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

假设我有一个列表中的水果列表。该列表的组织方式是,首先单词 'person' 将出现在列表中,并且该人之后的所有后续项目都是属于他们篮子的水果。然后列出的下一个人标志着一个解析时刻,为一个新人开始一个新的水果列表。最后,我希望将所有这些人的所有这些水果清单汇编成清单清单。果数、人数不详。然而,可以出现的水果类型是已知的。

如果上面的内容没有意义,这里有一个示例列表:

Person
Apple
Apple
Cherry
Apple
Orange
Person
Grape
Lemon
Apple
Apple

仅可用水果:苹果、樱桃、橙子、葡萄、柠檬

这是我对代码的尝试,我在我认为应该添加列表的地方使用了注释,但我不确定语法应该是什么(这就是我寻求帮助的原因):

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

我建议使用以下数据结构来表示您的数据:

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

你可以这样做:

  static class Program
  {
    static IEnumerable<KeyValuePair<string, List<string>>> SliceBy(this IEnumerable<string> data, string delimiter)
    {
      string key = null;
      List<string> values = null;

      foreach (var item in data)
      {
        if (item == delimiter)
        {
          if (key != null)
          {
            yield return new KeyValuePair<string, List<string>>(key, values);
          }
          key = item;
          values = new List<string>();
        }
        else
        {
          values.Add(item);
        }
      }

      if (key != null)
        yield return new KeyValuePair<string, List<string>>(key, values);
    }

    static void Main(string[] args)
    {
      var personFruits = new[] { "Person", "Apple", "Apple", "Cherry", "Apple", "Orange", "Person", "Grape", "Lemon", "Apple", "Apple", "Person", "Grape", "Lemon", "Apple", "Apple" };
      var result = personFruits.SliceBy("Person");

      foreach (var person in result)
      {
        Console.WriteLine(person.Key);
        foreach (var fruit in person.Value)
        {
          Console.WriteLine(fruit);
        }

        Console.WriteLine();
      }

    }
  }