在 .Split() 之后快速选择最后一个元素 [英] Select last element quickly after a .Split()
问题描述
我有这个代码:
stringCutted = myString.Split("/"). // ???
并且我想在 stringCutted
中存储 string[]
拆分后的最后一个元素,直接,快速,而不将拆分的数组存储在变量中并使用 array[array.length]
访问该元素.
and I'd like to store in stringCutted
the last element of the string[]
after the split, directly, quickly, without storing the splitted array in a variable and access to that element with array[array.length]
.
这在 C# 中可行吗?
Is this possible in C#?
推荐答案
如果您使用 .NET 3.5 或更高版本,使用 LINQ to Objects 很容易:
If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:
stringCutted = myString.Split('/').Last();
注意Last()
(没有谓词)针对源实现 IList
(就像一维数组那样)的情况进行了优化,因此它不会迭代整个数组查找最后一个元素.另一方面,这种优化没有记录......
Note that Last()
(without a predicate) is optimized for the case where the source implements IList<T>
(as a single-dimensional array does) so this won't iterate over the whole array to find the last element. On the other hand, that optimization is undocumented...
这篇关于在 .Split() 之后快速选择最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!