Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# smart way to delete multiple occurance of a character in a string

Tags:

c#

list

split

My program reads a file which has thousands of lines of something like this below "Timestamp","LiveStandby","Total1","Total2","Total3", etc.. each line is different What is the best way to split by , and delete the "" as well as put the values in a list

this is what I have

 while ((line = file.ReadLine()) != null)
  {
     List<string> title_list = new List<string>(line.Split(',')); 
  }

the step above still missing the deletion of the quotes. I can do foreach but that kinda defeat the purpose of having List and Split in just 1 line. What is the best and smart way to do it?

like image 554
John Ryann Avatar asked Jan 19 '26 21:01

John Ryann


2 Answers

The best way in my opinion is to use a library that parses CSV, such as FileHelpers.

Concretely, in your case, this would be the solution using the FileHelpers library:

Define a class that describes the structure of a record:

[DelimitedRecord(",")]
public class MyDataRecord
{
    [FieldQuoted('"')]
    public string TimeStamp;
    [FieldQuoted('"')]
    public string LiveStandby;
    [FieldQuoted('"')]
    public string Total1;
    [FieldQuoted('"')]
    public string Total2;
    [FieldQuoted('"')]
    public string Total3;
}

Use this code to parse the entire file:

var csvEngine = new FileHelperEngine<MyDataRecord>(Encoding.UTF8)
    { 
        Options = { IgnoreFirstLines = 1, IgnoreEmptyLines = true }
    };

var parsedItems = csvEngine.ReadFile(@"D:\myfile.csv");

Please note that this code is for illustration only and I have not compiled/run it. However, the library is pretty straightforward to use and there are good examples and documentation on the website.

like image 146
Cristian Lupascu Avatar answered Jan 21 '26 11:01

Cristian Lupascu


Keeping it simple like this should work:

List<string> strings = new List<string>();
while ((line = file.ReadLine()) != null) 
    string.AddRange(line.Replace("\"").split(',').AsEnumerable());
like image 31
naspinski Avatar answered Jan 21 '26 10:01

naspinski