Home > Back-end >  Accessing List values when having few strings inside a value
Accessing List values when having few strings inside a value

Time:12-15

So I have the following code:

  void ReadFromCsv()
            {

                using (var reader = new StreamReader(@"d:\test.csv", Encoding.Default))
                {
                    List<string> listA = new List<string>();
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        var values = line.Split(';');                    
                        listA.Add(values[0]);                      
                    }
                    Console.WriteLine(listA);         
                }
            }

which is reading from my csv file and an example of a line I get is:

50,2,10,201,10,9090339,24-OCT-21 09.38.38.679000 AM,123456789,24/10/2021 09:39:23,22/10/2021 09:39:37,Sm123456789-SM-20211031-VSR-000123.pdf,,,,,26/01/2022 13:08:58,,2,,0

first of all, why are there many commas around the end of the line? second of all, what if I wanted to access the value "10" (which is the 5th value ) of that string line, is that possible?, or going further, my task is to check for that 5th value and if its 5 for example, I'd want to take every row with 5thvalue=5 and create a csv for them, if 5thvalue=10 I want to create a csv for those records, and so on. but one task at a time, how do I access that value?

CodePudding user response:

1: commas around the end of the line mean first item of lines is empty ""

2: you can get 5th value as below:

 string _list = "50,2,10,201,10,9090339,24-OCT-21 09.38.38.679000 AM,123456789,24/10/2021 09:39:23,22/10/2021 09:39:37,Sm123456789-SM-20211031-VSR-000123.pdf,,,,,26/01/2022 13:08:58,,2,,0";

 var fiveIndex = _list.Split(',')[4];

3: then you can get list of lines that have a value of fiveIndex

var result =_list.Split(',').Select((v, i) => new { value = v, index = i }).Where(item => item.value == fiveIndex);

In your example, line 3 and line 5 have a value of 10(index=2, index=4). Then you can save these lines in csv file.

enter image description here

  • Related