I have a List<string>, and some of these strings are numbers. I want to extract this subset into a List<int>.
I have done this in quite a verbose looking way – as below – but I get the feeling there must be a neater LINQ way to structure this. Any ideas?
List<string> myStrs = someListFromSomewhere;
List<int> myInts = new List<int>();
foreach (string myStr in myStrs)
{
int outInt;
if (int.TryParse(myStr, out outInt))
{
myInts.Add(outInt);
}
}
Obviously I don’t need a solution to this – it’s mainly for my LINQ education.
You can do it like this:
This works because the execution of LINQ operators is deferred, meaning:
For each item in
myStrsfirst the code inWhereis executed and the result written intoparsed. And ifTryParsereturnedtruethe code inSelectis executed. This whole code for one item runs before this whole code is run for the next item.