+ 3

Remove element from comma separeted string and return new a comma separated string

I am trying to remove a element from a comma separated string. Input : "monkey,bear,cobra"; remove bear Output : "monkey, cobra"; if i do this step by step, it works string[] AnimalArray = AnimalString.Split(','); //split List<string> AnimalList = AnimalArray.ToList();//list AnimalList.Remove("bear");//remove element Console.WriteLine(String.Join(",", AnimalList.ToArray())); //recreate the comma-seperated string if I do this all on one line, I get this error 'bool' does not contain a definition for 'ToArray' string AnimalString2 = "monkey,bear,cobra"; Console.WriteLine(String.Join(",", AnimalString2.Split(',').ToList().Remove("bear").ToArray())); Where is the bool in this action ? What is the best way to do this ? https://code.sololearn.com/c7D1LIM26Tc3

20th Apr 2019, 10:22 PM
sneeze
sneeze - avatar
5 odpowiedzi
+ 4
The problem is in the ".ToArray()" call after the "Remove("bear")" call. The List class indeed has a remove method, which removes the element from the list. However, that remove method does not return a reference to the list itself; it returns a boolean value based on whether or not it succeeds in finding the specified value. You can see this if you call: Console.WriteLine(AnimalString2.Split(',').ToList().Remove("bear")); //output: "True" In other words, you can't cotinue to chain method-calls after the .Remove() call, since it does not return a reference to the underlying List object. Unfortunately, the call to Remove() has to be done on a separate line. The only way to get around this would be to write your own Remove function, which returns a reference to the List. This is why the error message is telling you "'bool' does not contain a definition for 'ToArray'". It's interpreting the code as: True.toArray() Which makes no sense to the compiler.
20th Apr 2019, 10:42 PM
Jack McCarthy
Jack McCarthy - avatar
+ 5
Jack McCarthy nailed it and here's what you can do with LINQ if you wish to exclude 🐻 from the list in one-line:- string.Join( ", ", AnimalString.Split(',') .Where( animal => animal != "bear") );
21st Apr 2019, 4:02 AM
Zephyr Koo
Zephyr Koo - avatar
+ 2
Thanks. Clear explanation.
20th Apr 2019, 10:44 PM
sneeze
sneeze - avatar
+ 1
Use a datastructure to operate performant on data sets. String is data and therefore imperformant for your purpose/algorithm.
21st Apr 2019, 12:18 PM
Daniel Adam
Daniel Adam - avatar
0
Daniel Adam Can you explain yourself more ? This is not a dataset or a database. It is a string in a protocol and the result should be a string a well. Why should i use dataset in such a small method ?
21st Apr 2019, 4:19 PM
sneeze
sneeze - avatar