-1

i've been given a data from txt file for example

Trans ID;Transaction Date;Cashier Name
00001;1 January;Ricky
00001;1 January;Ricky
00002;2 January;Rico

the problem is im new to this kind of file and dont know how to read and export it to a new txt file with separated Trans ID

So in this data, there will be 2 file , the first file is for the list of 00001 Trans ID , and the second file is for the list of 00002 file (or more trans ID to come)

I've tried to read the file

string filename = ("C:\\Users\\Documents\\My Received Files\\txn_success_daily.txt");
            string[] lines = File.ReadAllLines(filename);

            foreach (string line in lines)
            {
                string[] col = line.Split(new char[] { ';' });
            }

But i dont know how it works, because it different from excel(which basically i create apps to generate excel file)

I need to separate this data, into 2 txt file because it contains different transaction ID. Every different transaction ID, will create a new txt file and put the transaction in it (including the header) .

Thankyou

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49

1 Answers1

2
// read lines
var lines = File.ReadAllLines(@"D:\Tran.txt");

// group by first value
var groups = lines.Skip(1)
                  .Select(x => x.Split(';'))
                  .GroupBy(x => x[0]);

// iterate groups write the joined lines back to a new file with the key name
foreach (var group in groups)
   File.WriteAllLines($@"D:\Tran{group.Key}.txt", group.Select(x => string.Join(";", x)));

Add pepper and salt to taste.

It should be noted, you are better off using a dedicated CSV parser, as this could easily break

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • At first I thought `File.ReadLines` would be better, but then I realized the grouping requires it all in memory anyway. – Parrish Husband May 24 '19 at 04:05
  • sry, because i get the example data from my supervisor and its in .txt thats why im a bit confused , anyway thankyou so much, i'll try this –  May 24 '19 at 04:06
  • @ParrishHusband i thought as much too, if this is a mega file, then this might cause an issue, which would need a different solution – TheGeneral May 24 '19 at 04:08
  • Thankyou for the solution, it really works , didnt know can use something like linq for it –  May 24 '19 at 04:36