是否有一种简单的方法可以从数组中获取最后一项?例如,我可能有以下字符串数组:
var myArr1 = new string[]{"S1", "S2", "S3"};
var myArr2 = new string[]{"S1", "S2", "S3", "S4"};
我需要编写一个通用例程,它将为myArr1返回“S2.S3”,为myArr2返回“S3.S4”。使用Last()获取最后一项很容易,但似乎没有Last(-1)选项。有什么类似的吗?如果没有,那么最简单,最优雅的方法是什么?
答案 0 :(得分:2)
您可以使用此代码获取数组的倒数第二个元素......
myArr1[myArr1.Length - 2]
myArr2[myArr2.Length - 2]
输出
S2
S3
在线演示:http://rextester.com/AERTN64718
<强> 更新... 强>
myArr1[myArr1.Length - 2] + "." + myArr1[myArr1.Length - 1]
myArr2[myArr2.Length - 2] + "." + myArr2[myArr2.Length - 1]
或
myArr1[myArr1.Length - 2] + "." + myArr1.Last()
myArr2[myArr2.Length - 2] + "." + myArr2.Last()
输出
S2.S3
S3.S4
答案 1 :(得分:1)
This is based of off @Ehsan's answer (which was in VB, but I translated it to C#)
string LastTwoStrings(string[] array)
{
return (array[array.Length-2] + "." + array[array.Length-1]);
}
However, this WILL throw an exception if the array is smaller than 2.
答案 2 :(得分:1)
Using System.Linq you could do:
String.Join(".", arr.Skip(arr.Length - 2));
答案 3 :(得分:0)
这种需求是如此基本和直观,以至于我会考虑编写自己的Last(int)
扩展方法 - 恰好是你想象的方法 - 它可能看起来像这样:
public static class ExtensionMethods
{
public static IEnumerable<T> Last<T>(this IEnumerable<T> This, int count)
{
return This.Reverse().Take(count).Reverse();
}
}
然后你可以得到你需要的东西:
Console.WriteLine
(
string.Join(".", myArr1.Last(2))
);
哪个输出:
S2.S3
另一方面,如果您正在寻找效率,那么您应该使用数组和已知索引,这将更有效地使用IEnumerable
(必须扫描)。
public static IEnumerable<T> Last<T>(this T[] This, int count)
{
var i = This.Length;
if (count > i) count = i;
while (count-- > 0) yield return This[--i];
}
...完全相同,但只针对数组。