Jt2ouan
Jt2ouan

Reputation: 1962

read text file and writing to a list

Is their a way to split a text file in multiple places all at once and save to a list?

I was able to do the split in one place and write to a list like this:

var incomplete = File
            .ReadAllLines(path)
            .Select(a => a.Split(new[] { '|' }, StringSplitOptions.None)[5].Trim())
            .ToList();

I would like to split in four locations and then write to a list.

var mnbrs = File
            .ReadAllLines(path)
            .Select(a => a.Split('|')[2].Trim())
            .Select(b => b.Split('|')[5].Trim())
            .Select(c => c.Split('|')[6].Trim())
            .Select(d => d.Split('|')[11].Trim())
            .ToList();

this gives me error index was outside of bounds of array.

Any help is appreciated. Am also open to split and read filing in a different manner as well. I just would like to avoid reading file split once then to list then reading agian and splitting again and doing it four times.

Upvotes: 1

Views: 417

Answers (1)

mellamokb
mellamokb

Reputation: 56779

You want to do it in two steps. First split, then select the individual columns:

File
    .ReadAllLines(path)
    .Select(a => a.Split(new[] { '|' }, StringSplitOptions.None))
    .Select(a => new {
        Column1 = a[2].Trim(),
        Column2 = a[5].Trim(),
        Column3 = a[6].Trim(),
        Column4 = a[11].Trim()
    })
    .ToList();

Demo: http://ideone.com/aNyNT5

Upvotes: 6

Related Questions