前言
在 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[] { " 爱 & quot;," 情 & quot;," 公 & quot;," 寓 & quot;," 曾 & quot;," 小 & quot;," 贤 & quot;," 胡 & quot;," 一 & quot;," 菲 & quot;," 吕 & quot;," 子 & quot;," 乔 & quot;," 陈 & quot;," 美 & quot;," 嘉 & quot; };
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[] { " 爱 & quot;," 情 & quot;," 公 & quot;," 寓 & quot;," 曾 & quot;," 小 & quot;," 贤 & quot;," 胡 & quot;," 一 & quot;," 菲 & quot;," 吕 & quot;," 子 & quot;," 乔 & quot;," 陈 & quot;," 美 & quot;," 嘉 & quot; };
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[] { " 爱 & quot;," 情 & quot;," 公 & quot;," 寓 & quot;," 曾 & quot;," 小 & quot;," 贤 & quot;," 胡 & quot;," 一 & quot;," 菲 & quot;," 吕 & quot;," 子 & quot;," 乔 & quot;," 陈 & quot;," 美 & quot;," 嘉 & quot; };
Console.WriteLine(string.Join("",list[^2..^0]));
Console.WriteLine(string.Join("",list[^2..^6]));
|
to be continued…