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:
int parsed = 0;
myInts = myStrs.Where(x => int.TryParse(x, out parsed)).Select(x => parsed);
This works because the execution of LINQ operators is deferred, meaning:
For each item in myStrs
first the code in Where
is executed and the result written into parsed
. And if TryParse
returned true
the code in Select
is executed. This whole code for one item runs before this whole code is run for the next item.
LINQ and out
parameters don't mix well. You could do this:
var myInts = myStrs
.Select(s =>
{
int outInt;
return int.TryParse(s, out outInt) ? (int?)outInt : null;
})
.Where(i => i.HasValue)
.Select(i => i.Value)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With