Resolved How to split a string and add it to a list?

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
84
Programming Experience
Beginner
My data is like this
Export IdTax IdDelay Id
2342151​
645432|65444
544333​
78545​
90564​
34375​
856754​
37432​
9958|09866
73842​
43655​
NULL

I want to add the content of Tax Id and Delay Id into a list called Except. I need to split each element and then add it to the list. But when I am using the following code, it adds correctly upto 37432(col 2, row 4) but at col3,row4 , it overwrites everything and adds 9958,09866 and 43655.


C#:
 List<String> Excepted = new List<string>();

 if (Convert.ToInt32(fields[4]) > Convert.ToInt32(fields[5]))
                        {
                            if (fields[8] != "NULL")
                            {
                                if (fields[8].Contains('|'))
                                    Except = fields[8].Split('|').ToList();
                                else
                                Except.Add(fields[8]);

                            }


I don't want to do
C#:
Excepted.Add(Convert.ToString(fields[9].Split('|').ToList()));
as it is storing the value as System.Collections.Generic.List.
I am using the contents of my list to create a query later in the code.

C#:
 if (Excepted.Count > 0)
                {
                    string s = string.Empty;
                    string exceptQuery = "update excempt set column1 = '11' where itemid in(";

                    //foreach (string except in Excepted)
                    s = string.Join("','", Excepted);

                    exceptQuery = exceptQuery + "'" + s + "')";


                    using (StreamWriter streamWriter = new StreamWriter(outputpath + "Exempted" + ".txt"))
                    {
  
                                streamWriter.WriteLine(exceptQuery);
                            
                    }
                }
 
Last edited:
At line 8 you assign a new list to Except variable, instead use the (Except.)AddRange method to add the results from Split to the existing list.
 
Back
Top Bottom