There is a way to remove initial characters from every list without having to change their values one at a time?
No, it does not. The definition of the problem itself already indicates this. If you want to go through all the elements of the list to change your content the only way is to go through all the elements.
If the question was without using a loop I could say it depends. It’s virtually impossible to do without a loop, one way or another. The only way is to manually make each element, which is crazy.
Then you must be saying it, but the other answer showed that you can do it. But in fact you can’t. Can you hide the loop, as you can do in any function, as you can do whenever you create a abstraction. The point is that . NET already has an abstraction ready called LINQ.
What LINQ does is scroll through enumerable objects, as is the case with the list. How does it scroll through a list? Through a loop. There’s no magic, only she’s inside a method.
So is it always better to use LINQ? No. It depends on what you want to do. If you want to manipulate the data more complex, LINQ might not be a good one. If you need performance LINQ does not suit you well, it has a considerably higher cost when this is important. Test with both.
But this is the only cost? No, it creates a new list, makes new allocation and is inefficient and can cause unwanted breaks in the application more often.
Of course, all this depends on a number of factors, but if you use indiscriminately without knowing how each abstraction works will get involved in problems, so you need to understand everything and make the most appropriate decisions. Can’t be the choice of the cutest.
Is it much shorter and obvious? No, just a little, see the difference:
for (int i = 0; i < lista.Count; i++) if (s.Length > 3) lista[i] = lista[i].Substring(3);
lista = lista.Select(s => s.Length > 3 ? s.Substring(3) : s).ToList();
I put in the Github for future reference.
It doesn’t seem very clear what you want. The description is a bit confusing. Is there something wrong with your code? Is there anything else you want to do? Has some desired improvement?
– Maniero
In my application I always have new elements in the list of strings so I think it doesn’t pay to go through the whole list. It always has three initial characters in all strings and concatenates the number I want. I want to remove them and then convert to int. This is just one example.
– Felipe Mateus
That I understand, that’s very clear, but what do you want us to answer?
– Maniero
How to remove characters in a simpler way, without scrolling through the entire list, since I’m sure the characters will be present in all strings.
– Felipe Mateus
If you want to delete across the list how do you think it is possible to do this without going through the entire list? Impossible.
– Maniero