在.Split()之后快速选择最后一个元素 [英] Select last element quickly after a .Split()

查看:846
本文介绍了在.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆