在.Split()之后快速选择最后一个元素 [英] Select last element quickly after a .Split()
问题描述
我有此代码:
stringCutted = myString.Split("/"). // ???
,我想直接,快速地将拆分后的string[]
的最后一个元素存储在stringCutted
中,而不必将拆分后的数组存储在变量中,并使用array[array.length]
访问该元素.>
这在C#中可行吗?
如果您使用的是.NET 3.5或更高版本,则使用LINQ to Objects很容易:
stringCutted = myString.Split('/').Last();
请注意, Last()
(无谓词)已进行了优化.对于源实现IList<T>
的情况(就像一维数组一样),因此该不会遍历整个数组以查找最后一个元素.另一方面,该优化未记录在案...
I have this code :
stringCutted = myString.Split("/"). // ???
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]
.
Is this possible in C#?
If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:
stringCutted = myString.Split('/').Last();
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屋!