I have a text file that looks like this and I’m splitting at each ‘|’.
In between the 3rd ‘|’ is two words that I need to split into two separate columns. Having trouble doing the split.
Nbr| Address| Name |Phone|City|State|Zip
455 |gsgdgsg |fir last|434 |jk |jh |0393
I have something like this that is doing the split and writing the output to a list. Currently I can do the split and select the first part fine but when i do the split and select the second part I get index out of bounds of array error.
var Names = File
.ReadAllLines(path)
.Select(a => a.Split(new[] { '|' }, StringSplitOptions.None))
.Select(a => new {
phoneNbr = a[0].Trim(),
Name = a[2].Trim().Split(' ')[0],
Name2 = a[2].Trim().Split(' ')[1], //gives me error I think becuase it already split it
addr = a[1].Trim()
})
.ToList();
You probably do not have two words in column three with index 2 with some record. You need to enusure you get two elements after split before using second element.
Change
To