1、使用范围(range)索引获取数组
var array = new string[] { "C/C++/C#", "Java", "Python" }; var subArray = array[0..1];
Console.WriteLine(subArray[0]);
Console.WriteLine(subArray[1]);
2、使用范围(range)索引获取列表
列表本身不支持范围,可以创建扩展方法实现:
public static class ListExtensions
{
public static List<T> GetRange<T>(this List<T> list, Range range)
{
var (start, length) = range.GetOffsetAndLength(list.Count);
return list.GetRange(start, length);
}
}
调用方法:
var list = new List<string> { "C/C++/C#", "Java", "Python" }; var subList = list.GetRange(0..1);
Console.WriteLine(subList[0]);
Console.WriteLine(subList[1]);
或者
使用ToArray()实现范围索引:
var list = new List<string> { "C/C++/C#", "Java", "Python" };
var subList = list.ToArray()[0..1];
Console.WriteLine(subList[0]);
Console.WriteLine(subList[1]);
或者
var list = new List<string> { "C/C++/C#", "Java", "Python" };
var subList = list.GetRange(0,1);
Console.WriteLine(subList[0]);
Console.WriteLine(subList[1]);