C#LINQ:如何字符串(QUOT; [1,2,3] QUOT;)解析为一个数组? [英] C# LINQ: How is string("[1, 2, 3]") parsed as an array?
问题描述
我试图解析字符串到数组,并找到一个非常简洁的方法。
I am trying to parse a string into array and find a very concise approach.
string line = "[1, 2, 3]";
string[] input = line.Substring(1, line.Length - 2).Split();
int[] num = input.Skip(2)
.Select(y => int.Parse(y))
.ToArray();
我试图删除跳过(2),我不能得到,因为非INT字符串数组。我的问题是,什么是这些LINQ函数的执行顺序。多少次被跳过这里叫什么名字?
I tried remove Skip(2) and I cannot get the array because of non-int string. My question is that what is the execution order of those LINQ function. How many times is Skip called here?
先谢谢了。
推荐答案
该订单是您指定的顺序。因此, input.Skip(2)
跳过数组中的前两个字符串,因此只有最后遗迹,是 3
。可以分析到 INT
。如果删除跳到(2)
您正试图解析他们。这并不工作,因为逗号仍然存在。您已通过的空格分裂,但不会删除逗号。
The order is the order that you specify. So input.Skip(2)
skips the first two strings in the array, so only the last remains which is 3
. That can be parsed to an int
. If you remove the Skip(2)
you are trying to parse all of them. That doesn't work because the commas are still there. You have splitted by white-spaces but not removed the commas.
您可以使用 line.Trim('[',']')。斯普利特('');
和 int.TryParse
:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int i = 0;
int[] num = input.Where(s => int.TryParse(s, out i)) // you could use s.Trim but the spaces don't hurt
.Select(s => i)
.ToArray();
只是为了澄清,我已经使用 int.TryParse
只,以确保如果输入包含无效数据,你没有得到一个例外。它没有任何修复。它还将与 int.Parse
工作
Just to clarify, i have used int.TryParse
only to make sure that you don't get an exception if the input contains invalid data. It doesn't fix anything. It would also work with int.Parse
.
更新:作为已被证明通过埃里克利珀的在注释部分在LINQ查询中使用 int.TryParse
可能是有害的。因此,最好使用一个封装 int.TryParse
并返回可空℃的helper方法; INT>
。因此,一个扩展是这样的:
Update: as has been proved by Eric Lippert in the comment section using int.TryParse
in a LINQ query can be harmful. So it's better to use a helper method that encapsulates int.TryParse
and returns a Nullable<int>
. So an extension like this:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
现在,你可以在这样一个LINQ查询使用它:
Now you can use it in a LINQ query in this way:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int[] num = input.Select(s => s.TryGetInt32())
.Where(n => n.HasValue)
.Select(n=> n.Value)
.ToArray();
这篇关于C#LINQ:如何字符串(QUOT; [1,2,3] QUOT;)解析为一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!