使用Linq将字符串解析为int []

问题描述 投票:0回答:1

我来自this问题,但我的字符串中也可能存在无效值。例如

string input = "1;2;3;4;5;6x;7;8;9;1x0";

由于[1,2,3,4,5,7,8,9]是无效的整数值,因此应结果为["6x", "1x0"] >>

我的方法:https://dotnetfiddle.net/Ji4bzq

string i = "1;2;3;4;5;6x;7;8;9;1x0";
int temp = -1;
int[] r = i.Split(';').Where(x => int.TryParse(x, out  temp)).Select(_ => temp).ToArray();

这似乎有效,但是由于该Select(_ => temp)部分而感觉有点不对。

问题:

在可读性和可靠性方面,还有更好的方法吗? (AsParallel应该在此处失败)

我来自这个问题,但是我的字符串中也可能存在无效值。例如字符串输入=“ 1; 2; 3; 4; 5; 6x; 7; 8; 9; 1x0”;应该结果为[1,2,3,4,5,7,8,9],因为[“ 6x”,“ 1x0”]是...

c# arrays string linq parsing
1个回答
1
投票

如果使用C#7.0,则可以使用var out feature

© www.soinside.com 2019 - 2024. All rights reserved.