Max Li
Max Li

Reputation: 5199

How to index with colon in c#

I want to access an instance of the class with the syntax like A[:,2] which is quite widespread among programming languages.

Assume, I have some class ClassA with a 2-dimensional double array in its property Content and created an instance A of it.

If I want to access A.Content[2,3] by A[2,3], I need to build inside the ClassA this method:

public double this[int i, int j]
{
    get
    {
        return this.Content[i,j];
    }
    set
    {
        this.Content[i,j]=value;
    }
}

Now, I can do "A[2,3]".
As the next step, I also would like to do "A[2,:]" (the output will be the 1-dimensional array), how can I implement it?

Upvotes: 0

Views: 750

Answers (1)

Steve B
Steve B

Reputation: 37660

I don't believe it's possible as there is no such syntax (as far as I know) in the C# language.

Maybe you can use some method GetRow(2) or something like this.

public double[] GetRow(int rowNumber)
{
    var result = new double[this.Content.GetLength(0)];
    for(var i=0; i<result.Length; i++)
    {
        result[i] = this.Content[rowNumber, i];
    }
    return result;
}

The same logic for a GetColumn should be straightforward.

Upvotes: 2

Related Questions