Search code examples
c#arraysstring-parsingfileparsing

Parsing a text file concatenate a string if the first element is always the same


I have a file with this format :

**000002650**,00254,001,
**000002650**,02000,001,
**000002650**,02001,001,
000003781,00000,001,
000007790,00245,001,
000007790,02000,001,
000007790,02001,001,
000007907,00245,001,
000007907,02000,001,
000007907,02001,001,
000007998,00000,001,

and I have to get this file format

HI:**2650**,254,2000,2001
HI:3781
HI:7790,245,2000,2001

So when the first element is equal to the next first element to next row I have to concat all element different

how can I do in c# ?

My code now

using (StreamReader reader = new StreamReader(path))
                    {
                                                string sFile = string.Empty;
                        sFile = reader.ReadToEnd();


                        string[] asLine = sFile.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);


                        StringBuilder stringBuilder = new StringBuilder();

                        foreach (string sLine in asLine)
                        {

                            string[] asSegments = sLine.Split(',');

                            firstTemp = asSegments[1];

                            if (firstTemp == asSegments[1])
                            {
                                stringBuilder.Append()
                            }


                        } 

                    } 

Solution

  •         string[] lines = File.ReadAllLines(path);
            Dictionary<string, List<string>> collection = new Dictionary<string, List<string>>();
            foreach (var line in lines)
            {
                string[] tokens = line.Split(',');
                if (tokens.Length > 1)
                {
                    if (collection.ContainsKey(tokens[0]))
                    {
                        collection[tokens[0]].Add(tokens[1]);
                    }
                    else
                    {
                        collection.Add(tokens[0], new List<string> { tokens[1] });
                    }
                }
            }