Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to extract ints from a list of strings

Tags:

c#

list

linq

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.

like image 207
jlb83 Avatar asked Jan 18 '12 13:01

jlb83


2 Answers

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.

like image 85
Daniel Hilgarth Avatar answered Nov 16 '22 17:11

Daniel Hilgarth


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();
like image 25
dtb Avatar answered Nov 16 '22 16:11

dtb