I have this string:
string input = "1,2,3,4,s,6";
Pay attention to the s
character.
I just want to convert this string in a List<int>
using LINQ. I initially tried in this way:
var myList = new List<int>();
input.Split(',').ToList().ForEach(n =>
myList.Add(int.TryParse(n, out int num) ? num : -1)
);
lista.RemoveAll(e => e == -1);
But I prefer not have any -1
instead of a no-number characters.
So now I try with this:
var myList = new List<int>();
input.Split(',').ToList()
.FindAll(n => int.TryParse(n, out int _))
.ForEach(num => myList.Add(int.Parse(num)));
I prefer this, but is really a shame that the parsing happening two times (TryParse
at first and then Parse
). But, from what I understand, the out variable in TryParse is useless (or not?).
Have you others suggests (using LINQ)?
Here's a generic LINQ extension, which utilizes a
delegate
. This will allow you to pass in a function returning abool
, while "retaining" the result of theout
variable (likeint.TryParse
).Usage:
Code:
It doesn't return a
List<int>
but I have to draw the line somewhere. You can make a list out of it.You can do it like this:
Why does it have to be LINQ?
Try:
Fiddle
.Split(...).ToList()
asString[]
is already enumerable.FindAll
,ForEach
andRemoveAll
methods are not Linq methods, they're members ofList<T>
. Their Linq equivalent isWhere
.Like so:
You can make it more concise with a helper method:
Becomes:
If you don't want to reserve
-1
then you can use nullable ints:Using a nice extension method
(which you can replace with
new[] { n }
if preferred)