Convert a string in a List using LINQ (cleane

2019-06-05 10:01发布

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)?

8条回答
Emotional °昔
2楼-- · 2019-06-05 10:56

I prefer to make a nice helper function:

Func<string, int?> tryParse = s => int.TryParse(s, out int n) ? (int?)n : null;

Then it's a simple matter to parse:

string input = "1,2,3,4,s,6";

List<int> myList =
    input
        .Split(',')
        .Select(s => tryParse(s))
        .Where(n => n.HasValue)
        .Select(n => n.Value)
        .ToList();

That gives:

1 
2 
3 
4 
6 
查看更多
闹够了就滚
3楼-- · 2019-06-05 10:58
int i = 0; 
var myList = (from s in input.Split(',') where int.TryParse(s, out i) select i).ToList();

If the numbers are always single ASCII digits:

var myList = "1,2,3,4,s,6".Select(c => c ^ 48).Where(i => i < 10).ToList();

Few slower RegEx alternatives for fun:

var myList2 = Regex.Split("1,2,3,4,s,6", "[^0-9]+").Select(int.Parse).ToList(); // if the string starts and ends with digits

var myList3 = Regex.Replace("1,2,3,4,s,6", "[^0-9]+", " ").Trim().Split(' ').Select(int.Parse).ToList();

var myList4 = Regex.Matches("1,2,3,4,s,6", "[0-9]+").Cast<Match>().Select(m => int.Parse(m.Value)).ToList();
查看更多
登录 后发表回答