前言
在C#8.0中新增了两个新的特性,System.Index
及System.Range
,这是借助对应的两个运算符 ^
及 ..
,让我们很方便就可以获取序列中某个或一段元素。
正文
System.Index
System.Index表示索引类型,^
指定的索引是相对于序列尾端。如^2
表示从序列尾端、从右至左的第二个元素。这里始终记住 ^x
等价于 list.length - x
,所以如果代码写成 list[^0],那么等价于 list[list.length-0],结果就会抛出异常。下边举例说明。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var list = new[] { "爱","情","公","寓","曾","小","贤","胡","一","菲","吕","子","乔","陈","美","嘉" };
System.Index index1 = 0; System.Index index2 = ^0;
var idx3 = ^1;
Console.WriteLine(list[idx1]);
Console.WriteLine(list[idx2]);
Console.WriteLine(list[idx3]);
Console.WriteLine(list[^2]);
|
System.Range
System.Range表示序列的子范围,使用运算符x..y
,表示取序列中x到y的一段数据,但不包括y。再举例说明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var rng1 = ..; var rng2 = 2..; var list = new[] { "爱","情","公","寓","曾","小","贤","胡","一","菲","吕","子","乔","陈","美","嘉" };
Console.WriteLine(string.Join("",list[rng1]));
Console.WriteLine(string.Join("",list[rng2]));
Console.WriteLine(string.Join("",list[2..4]));
Console.WriteLine(string.Join("",list[..4]));
|
混合使用 Index、Range
1 2 3 4 5 6 7 8 9 10 11
| var list = new[] { "爱","情","公","寓","曾","小","贤","胡","一","菲","吕","子","乔","陈","美","嘉" };
Console.WriteLine(string.Join("",list[^2..^0]));
Console.WriteLine(string.Join("",list[^2..^6]));
|
to be continued…