static T ByIndex2<T>(T[][] arr, int index)
{
foreach (var item in arr)
{
if (index - item.Length < 0) // если разница меньше 0, значит нашли массив, а index соответствует индексу нужного элемента в найденном массиве
{
return item[index];
}
index -= item.Length;
}
throw new IndexOutOfRangeException(nameof(index));
}
static class ArrayExtensions {
public static T GetValueAt<T>(this T[][] arr, int index) {
int currentIndex = 0;
foreach (T[] arr1 in arr) {
foreach (T i in arr1) {
if (currentIndex == index)
return i;
currentIndex++;
}
}
throw new IndexOutOfRangeException();
}
}
用法:
int[][] arr = new int[][] { new int[] { 0, 1, 2, 3 }, new int[] { 4, 5, 6 } };
Console.WriteLine(arr.GetValueAt(5)); //=> 5
没有解决这个问题的标准机制。而且计算矩形数组索引的公式也不合适。
只有一个解决方案:遍历数组并计算元素。
实现可以在额头:
Where
SelectMany使数组平坦,但ElementAt在指定索引处获取元素。如果不计算每个元素,则可以改进,但立即评估元素位于哪个数组中
用法: