I want to convert a List
to a List
.
Here is my code:
void Convert(List stringList)
{
Your method works fine, so I am assuming you are a beginner developer who is still learning the syntax of the language. I will not give you the advanced LINQ solution just yet, but help you achieve what you want with your current code. You are currently not returning the list you are creating, so change the method signature from:
void Convert(List stringList)
to:
List Convert(List stringList)
and at the very end just before the method ends add:
return intList;
Then in your code you can call it like so:
List strings = new List { "1", "2", "3" };
List integers = this.Convert(strings);
Note: If you don't want your code to throw an exception, might I suggest using TryParse
instead of Parse
, be careful however since this method works slightly differently and makes use of out
parameters. You can learn more about it here.
If you are interested in LINQ, @Peter Kiss's solution is as good as it gets. He is using LINQ with method syntax, but there's also SQL-like syntax which you may or may not find easier to grasp. A good introduction to LINQ can be found here.