简体   繁体   中英

Removing Columns From A Pipe Delimited File C#

I have a pipe delimited file with the following columns

Col0|Col1|Col2|Col3|Col4|Col5|Col6
data|data|data|data|data|data|data
data|data|data|data|data|data|data
data|data|data|data|data|data|data
data|data|data|data|data|data|data

I want to remove columns from a pipe delimited file.

        //THIS code will remove Col2
        string[] csvLines = File.ReadAllLines(@"Input.txt");


        string header = csvLines.FirstOrDefault(l => !String.IsNullOrWhiteSpace(l));
        if (header != null)
        {

                IEnumerable<string> allButWantedCols=null;

                allButWantedCols = csvLines
                       .Select(l => new { Columns = l.Split(new[] { '|' }, StringSplitOptions.None) })
                       .Where(x => x.Columns.Length > 2)
                       .Select(x => string.Join("|", x.Columns
                       .Where((col, index) => index != 2)
                       .Select(col => col.Trim())));

                // rewrite the file with all columns but balance:
                File.WriteAllLines(@"pipe_OUTPUT_.txt", allButWantedCols);

        }

The code above removes "Col2" and all of its data.

I am struggling to figure out how to remove multiple columns?

ie remove columns Col2,Col3,Col6

This is your current code:

allButWantedCols = csvLines
                       .Select(l => new { Columns = l.Split(new[] { '|' }, StringSplitOptions.None) })
                       .Where(x => x.Columns.Length > 2)
                       .Select(x => string.Join("|", x.Columns
                       .Where((col, index) => index != 2)
                       .Select(col => col.Trim())));

Change it to something along the lines of the below.

allButWantedCols = csvLines
                       .Select(l => new { Columns = l.Split(new[] { '|' }, StringSplitOptions.None) })
                       .Where(x => x.Columns.Length > 2)
                       .Select(x => string.Join("|", x.Columns
                       .Where((col, index) => index != 2 && index != 3 && index != 6)
                       .Select(col => col.Trim())));

You will potentially want to ensure that columns exist at said indexes first, but that should provide you what you've asked about in your initial question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM