gpt4 book ai didi

C# 林奇 : How is string ("[1, 2, 3]") parsed as an array?

转载 作者:太空狗 更新时间:2023-10-30 00:24:08 25 4
gpt4 key购买 nike

我正在尝试将字符串解析为数组并找到一种非常简洁的方法。

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();

我尝试删除 Skip(2),但由于非整数字符串而无法获取数组。我的问题是那些 LINQ 函数的执行顺序是什么。这里调用了多少次 Skip?

提前致谢。

最佳答案

顺序是您指定的顺序。所以input.Skip(2)跳过数组中的前两个字符串,因此只剩下最后一个 3 .可以解析为 int .如果删除 Skip(2)您正在尝试解析所有这些。这不起作用,因为逗号仍然存在。您已按空格分隔但未删除逗号。

你可以使用 line.Trim('[', ']').Split(',');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 .

更新:Eric Lippert 已证明 in the comment section使用 int.TryParse在 LINQ 查询中使用可能是有害的。所以最好使用封装int.TryParse的辅助方法并返回 Nullable<int> .所以像这样的扩展:

public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}

现在您可以通过这种方式在 LINQ 查询中使用它:

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# 林奇 : How is string ("[1, 2, 3]") parsed as an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28988523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com