使用AddRange将一列二维数组添加到列表框中



我有一个2D阵列:

string[,] table = new string[100,2];

我想把表[,0]添加到列表框中,类似于

listbox1.Items.AddRange(table[,0]);

这样做的诀窍是什么?

编辑:我想知道是否可以使用AddRange

为了可读性,您可以为数组创建扩展方法。

public static class ArrayExtensions
{
    public static T[] GetColumn<T>(this T[,] array, int columnNum)
    {
        var result = new T[array.GetLength(0)];
        for (int i = 0; i < array.GetLength(0); i++)
        {
            result[i] = array[i, columnNum];
        }
        return result;
    }
}

现在,您可以轻松地将范围添加为数组中的切片。请注意,您可以从原始数组中创建元素的副本。

listbox1.Items.AddRange(table.GetColumn(0));

最新更新