gpt4 book ai didi

c# - 访问数组项?

转载 作者:行者123 更新时间:2023-11-30 15:11:24 25 4
gpt4 key购买 nike

我有一个变量包含:
有时是字符串数组,有时是字符串数组
例如:

var words = a LINQ to XML query;
//words == { "01", "02", "03", ... }
//or
//words == { {"01", "02", "03"}, {"04", "05", "06"}, ... }

现在,我想使用 for 语句
访问 words 数组中的每个项目你能指导我吗?
谢谢

最佳答案

(注:请看编辑...)

如果您事先并不知道您得到的是字符串数组还是字符串数组,则需要有条件地调用SelectMany:

string[][] multi = words as string[][];
string[] flattened = multi == null ? words : multi.SelectMany(x => x).ToArray();

请注意,在这种情况下,如果您更改flattened 的内容,那将更改words(如果它已经是扁平的)或只需更改一个副本(如果它是一个锯齿状数组)。如果你想让它保持一致,你可以在条件运算符的第二个操作数中调用 words.ToArray():

string[] flattened = 
multi == null ? words.ToArray() : multi.SelectMany(x => x).ToArray();

有没有办法避免一开始就模棱两可?特别是,如果您可以控制所涉及的 LINQ to XML 查询,您应该能够使它们提供一致的结果类型。

编辑:我刚刚意识到,如果您不知道开始的数据类型,那么 words 大概被声明为 object 或者也许IEnumerable。在那种情况下,你会想要这样的东西:

public string[] Flatten(object words)
{
string[][] multi = words as string[][];
if (multi != null)
{
return multi.SelectMany(x => x).ToArray();
}
string[] single = words as string[];
if (single != null)
{
return single.ToArray(); // Defensive copy; remove if not needed
}
throw new ArgumentException("Argument must be string[] or string[][]");
}

这仍然非常棘手 - 您绝对应该尝试让查询为您提供一些一致的结果类型。

关于c# - 访问数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2415155/

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