C#如何用数组填充2D数组? [英] C# how to fill a 2D array with an array?

查看:97
本文介绍了C#如何用数组填充2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种用阵列填充2D数组的智能方法。 2D阵列是具有行和单元格的网格。单元格的输入(字符串)来自Console.ReadLine()。所以我将字符串拆分为字符串数组,现在我想使用这个字符串数组来填充数据数组的第二维。





I'm looking for a smart way to fill a 2D array with an array. The 2D array is a grid with rows and cells. The input (a string) for the cells come from Console.ReadLine(). So I split the string to an string array and now I want to use this string array to fill the 2nd dimension of the data array.


string[,] data = new string[height, width]; //grid

for (int i = 0; i < height; i++)
{
    string[] line = Console.ReadLine().ToCharArray().Select(c => c.ToString()).ToArray();
    
    data[i] = line; // <- compiler don't like this
}







示例:

输入字符串为abc。



行看起来像

行[0] ==a

行[1] ==b

line [2] ==c



现在我想要这个

数据[0] [0] ==a

数据[0] [1] ==b

数据[0] [2] ==c



我尝试了什么:



当然,我可以使用'for',但是这种情况下每一个表现都很重要。




Example:
the input string is "abc".

line looks like
line[0] == "a"
line[1] == "b"
line[2] == "c"

now I want to have this
data[0][0] == "a"
data[0][1] == "b"
data[0][2] == "c"

What I have tried:

Sure, I could use 'for', but in this case every piece of performance is important.

推荐答案

你能不能使用'addRange' - Array.addRange函数 [ ^ ]?
can you not use 'addRange' - Array.addRange Function[^] ?


我。使用扩展方法:这里我们只是打包你用for循环做的事情:
I. Using an Extension Method: here we're just packaging up what you'd do with a for-loop:
public static class ArrayExtensions
{
    public static void Array2dInsert<T>(this T[,] ary, int rowndx, int startcol, params T[] values)
    {
        if (ary.GetLength(0) < rowndx
            || ary.GetLength(1) < startcol)
        {
           throw new ArgumentOutOfRangeException("rowndx or startcol", "Error in Array2dInsert: Out of range row or column index");
        }

        if(values.Length > ary.GetLength(1) - startcol)
        {
           throw new ArgumentOutOfRangeException("values", "Error in Array2dInsert: Too many values");
        }

        foreach (var value in values)
        {
            ary[rowndx, startcol] = value;
            startcol++;
        }
    }
}

测试:在某些Method或EventHandler中执行此代码

Test: execute this code in some Method or EventHandler

int[,] intary = new int[2,6];

intary.Array2dInsert(0,0,100,200,300);

请注意,使用此扩展方法,您可以在要开始插入值的数组的行中指定索引。



II。使用带有自定义索引器的类:



我强烈建议您在开始阅读之前学习以下教程:[ ^ ],[ ^ ]。



并且,请在CodeProject上查看关于Indexers的一些文章:[ ^ ]。



请记住,在.NET内部,Indexer 方法。



首先,让我们看看可以做些什么,但是,imho,不应该这样做:

Note that with this Extension Method you can specify the index in the "row" of the Array you wish to start inserting values at.

II. using a Class with custom Indexers:

I strongly suggest you study the following tutorials before you start reading this: [^],[^].

And, do review some of the many articles on Indexers here on CodeProject:[^].

Keep in mind that, internally in .NET, an Indexer is a Method.

First, let's look at what can be done, but, imho, should not be done:

using System.Collections.Generic;

namespace ArrayUtilities
{
    public class Array2dEx<T>
    {
        private T[,] innerArray { set; get; }

        public Array2dEx(int sz1, int sz2)
        {
            innerArray = new T[sz1, sz2];
        }

        //  one value only indexer
        public T this[int ndx1, int ndx2]
        {
            get
            {
                return innerArray[ndx1, ndx2];
            }
            set
            {
                innerArray[ndx1, ndx2] = value;
            }
        }

        // multiple value indexer
        public  IEnumerable<T> this[int ndx1, params T[] args]
        {
            set
            {
                for (int i = 0; i < args.Length; i++)
                {
                    innerArray[ndx1, i] = args[i];
                }
            }
            
            get
            {
                for (int j = 0; j < innerArray.GetLength(1); j++)
                {
                    yield return innerArray[ndx1, j];
                }
            }
        }
    }
}

使用此类的示例:

// in some Method or EventHandler

Array2dEx<string> test1 = new Array2dEx<string>(4, 5);

// put a break-point here

test1[0, 0] = "hello";
test1[0, 1] = "goodbye";

// note 1
string[] testary = new string[] { "what", "where" };
test1[2, testary] = null;

// note 2
var row2 = test1[2];

var row2item2 = test1[2, 1];

我建议你将上面的代码复制到.NET项目中,并在指定的位置放置一个断点,然后逐步执行代码,检查值每个步骤。



Class'Array2dEx是一个泛型类,它包含您指定的Type的2d数组,并提供两种不同的索引方法。一种索引方法是标准索引方法的替代,正是您对二维数组索引的期望。



注1:第二种索引方法使用事实上,自定义索引器可以采用任意参数,包括,如本例所示,任意大小的参数列表(使用'params参数工具)。



请注意,第二个Indexer的setter不使用任何Property提供的'value参数;我们使用'null作为扔掉的论点。更多关于这一点,后来:setter在被调用时必须传递一些值。



注2:这里索引器的'getter部分返回一个IEnumerable< T>



为什么你不应该这样做:



1.这很奇怪,hackish并绕过处理数组的常用语法。



2.未来的其他人可能会查看代码并想知道正在发生什么似乎正在分配'对于括号中不寻常的东西,这是空的。



...继续,明天......如果使用锯齿状数组,可以使用什么,我觉得好多了。

I suggest you copy the above code into a .NET project, and put a break-point at the place indicated and then step through the code, inspecting the values with each step.

The Class 'Array2dEx is a generic Class that holds a 2d Array of a Type you specify, and provides two different indexing methods. One indexing method is a replacement for the standard indexing method, and is exactly what you'd expect from a 2d Array index.

Note 1: the second indexing method uses the fact that a custom indexer can take arbitrary parameters, including, as shown in this case, a list of parameters of any size (using the 'params argument facility).

Note that the setter of the second Indexer does not make use of the 'value parameter that any Property provides; we used 'null as a "throw-away" argument. More about that, later: a setter must have some value passed to it when it's called.

Note 2: here the 'getter part of the indexer returns an IEnumerable<T>

Why you should not do this:

1. It's weird, "hackish," and bypasses the usual syntax for dealing with Arrays.

2. someone else in the future may look at the code and wonder what's going on with what appears to be assigning 'null to the unusual "stuff" between brackets.

... to be continued, tomorrow ... what you could use if you used a jagged Array, that I think is much better.


这篇关于C#如何用数组填充2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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