Home > Blockchain >  How to split IEnumerable<string> to groups by separator?
How to split IEnumerable<string> to groups by separator?

Time:02-21

I have IEnumerable<string> which represents txt file.
Txt file have this structure:
Number of group ( int )
WordOfGroup1 (string)
WordOfGroup2
WordOfGroupN
EmptyLine
Number of group ( int )
WordOfGroup1 (string)
etc.

I need create from this text Dictionary<fistWordOfGroup(string), allWordsInGroup(List<string>)
How i can make that in linear complexity?

CodePudding user response:

Try the algorithm below. This will add a group of words to the dictionary whenever it comes across an empty line.

List<string> input = new List<string>()
{
    "1",
    "wordOfGroup11",
    "wordOfGroup12",
    "wordOfGroup1N",
    "\n",
    "2",
    "wordOfGroup21",
    "wordOfGroup22",
    "\n"
};


Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
string firstWordOfGroup = "";
List<string> allWordsInGroup = new List<string>();

foreach (string line in input)
{
    if (int.TryParse(line, out int index) == true)
    {
        allWordsInGroup.Clear();
        continue;
    }
    // I don't know what "EmptyLine" means
    if (line == "\n" || line == Environment.NewLine || line == string.Empty)
    {
        result.Add(firstWordOfGroup, allWordsInGroup);
    }
    else
    {
        if (allWordsInGroup.Count == 0)
        {
            firstWordOfGroup = line;
        }

        allWordsInGroup.Add(line);
    }
}

Also note that if your groups can have the same first word (e.g. both starting with "WordOfGroup1" then you should use a List<KeyValuePair<string, List<string>>> because the dictionary does not store duplicate keys.

  •  Tags:  
  • c#
  • Related