Paul Meems
Paul Meems

Reputation: 3284

How to convert multi-dim array to generics collection in C#

I'm trying to refactor some old code that is heavily relying on multi dimensional arrays. I'm having problems when I need to read a lot of data. I already found I should use generic collections instead. But I can only find samples for simple arrays.

Here's part of the code to clearify:

// Declare:
private double[,] cpoints;

// Init:
this.cpoints = new double[this.Np, 3];

// Writing:
this.cpoints[indx, 0] = x;
this.cpoints[indx, 1] = y;
this.cpoints[indx, 2] = z;

// Reading:
double dx = this.cpoints[0, 0] - this.cpoints[1, 0];

The first dimension of the array can be very large. Because of my search I think I need a List in a Dictionary, but I can't get it right.

Can anybody point me in the right direction? Some samples would really be great.

BTW. I'm using VS2008 and .NETv3.5

EDIT:

The code is part of a Kriging implementation for the MapWindow Open Source GIS application (www.mapwindow.org). This plug-in is working OK with small amounts of points, but with larger amounts we're getting memory issues. At What is the Maximum Size that an Array can hold? I read that it is better to use List so I'm trying to refactor the code so it can handle more points. The answer by Damith seems good. I'll try that. The code has more multi-dim arrays. I'll need to look at those as well. Most likely I'll ask some questions about them later on ;)

Thanks.

Upvotes: 0

Views: 586

Answers (1)

Damith
Damith

Reputation: 63095

public class CPoint
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }
}

Declare:

private List<CPoint> cpoints;

Init:

this.cpoints = new List<CPoint>(this.Np);

Writing:

this.cpoints[indx].X = x;

Reading:

double dx = this.cpoints[0].X - this.cpoints[1].X;

you can change the class below as well

public class  CPoint<T>
{
    public T X { get; set; }
    public T Y { get; set; }
    public T Z { get; set; }
}

then you can use othe types like int

var cpoints = new List<CPoint<int>>(45);

int dx = cpoints[0].X - cpoints[1].X;

Upvotes: 2

Related Questions