Search code examples
c#linq

Convert foreach loop with nested if-else into Linq expression


This is the problem I'm trying to solve first of all: Convert a string like "1, 2, 3" into a List<int> If there are non-numeric characters besides spaces and ',' then add int.MinValue to the list instead.

So if the string is "abc, 2, 3", then it should return a List<int> with "-2147483648, 2, 3"

This is the code I have so far that does what I wrote above.

public static IList<int> ConvertToListInt(string data)
{
    var list = new List<int>();
    var nums = data.Split(',');
    foreach (var item in nums)
    {
        if (int.TryParse(item, out var num))
        {
             list.Add(num);
        } 
        else
        {
            list.Add(int.MinValue);
        }
    }

    return list;
}

Would it be possible to replace the code inside ConvertToListInt with a LINQ expression?


Solution

  • You can just move it into the Select expression:

    var list = data.Split(',')
        .Select(item => int.TryParse(item, out var num) ? num : int.MinValue)
        .ToList();