How to convert List<string> to List<int> where empty or null string to be converted as 0 using LINQ in C#
Following LINQ statements will convert the List<sting> to List<int> but do these statements work for above mentioned scenario
listofIDs.Select(int.Parse).ToList()
var intList = stringList.Select(s => Convert.ToInt32(s)).ToList()
Here’s my pitch:
Test output: 1,2,0,0
Not dissimilar to the IsNullOrWhiteSpace suggestion. However, it’s safer than just using int.Parse unguarded, which will throw an exception if given invalid input.
A suggestion for you: TDD! Get familiar with one of the many .NET testing frameworks. You can answer questions like yours with another 2-3 lines of code.