衍合1的数组在C# [英] Rebase a 1-based array in c#

查看:196
本文介绍了衍合1的数组在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的数组是从1开始的(从一个Excel范围调用的get_value产生 我得到一个二维数组例如:

I have an array in c# that is 1-based (generated from a call to get_Value for an Excel Range I get a 2D array for example

object[,] ExcelData = (object[,]) MySheet.UsedRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);

这似乎是一个数组例如ExcelData [1..20,1..5]

this appears as an array for example ExcelData[1..20,1..5]

有没有办法告诉编译器变基,这样我就不需要加1循环计数器的全部时间?

is there any way to tell the compiler to rebase this so that I do not need to add 1 to loop counters the whole time?

List<string> RowHeadings = new List<string>();
string [,] Results = new string[MaxRows, 1]
for (int Row = 0; Row < MaxRows; Row++) {
    if (ExcelData[Row+1, 1] != null)
        RowHeadings.Add(ExcelData[Row+1, 1]);
        ...
        ...
        Results[Row, 0] = ExcelData[Row+1, 1];
        & other stuff in here that requires a 0-based Row
}

这使事情变得不可读写的阵列将从零开始创建一个数组时,由于

It makes things less readable since when creating an array for writing the array will be zero based.

推荐答案

为什么不只是改变你的指数?

Why not just change your index?

List<string> RowHeadings = new List<string>();
for (int Row = 1; Row <= MaxRows; Row++) {
    if (ExcelData[Row, 1] != null)
        RowHeadings.Add(ExcelData[Row, 1]);
}

编辑:下面是将从原来的创建一个新的,从零开始的数组(基本上它只是创建了一个新的数组,它是一个元素小,拷贝到新阵列扩展方法所有元素,第一个元素,你正在跳过无论如何):

Here is an extension method that would create a new, zero-based array from your original one (basically it just creates a new array that is one element smaller and copies to that new array all elements but the first element that you are currently skipping anyhow):

public static T[] ToZeroBasedArray<T>(this T[] array)
{
    int len = array.Length - 1;
    T[] newArray = new T[len];
    Array.Copy(array, 1, newArray, 0, len);
    return newArray;
}

话虽这么说,你需要考虑,如果创建一个新的数组的惩罚(无论多小)是值得改进的code的可读性。我不是一个判断(它很可能是值得的),我只是确保你没有这个code运行,如果它会伤害你的应用程序的性能。

That being said you need to consider if the penalty (however slight) of creating a new array is worth improving the readability of the code. I am not making a judgment (it very well may be worth it) I am just making sure you don't run with this code if it will hurt the performance of your application.

这篇关于衍合1的数组在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆