Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array, Arraylist or list of lists?

I was going to use a standard array, I need it to x number of rows and be 2 columns

double[,] members = new double[x, 2];

and loop through all the results I get back and then add them to the array, but as the number of results can change I don't want to pre-define the size of the array...

members[0, 0] = cost;
members[x, 1] = tax;
x++;

I was looking at resizing the array but would it be easier just using an arraylist or list of lists for this?

like image 805
Standage Avatar asked Aug 04 '26 14:08

Standage


2 Answers

I would have a list of some type, where that type has a cost and a tax.

If space is a premium, it could be a struct with two doubles (btw, would decimal be more appropriate? It is almost always is a better choice for money), but if so: make it immutable.

For example:

public struct YourType {
    private readonly decimal cost, tax;
    public decimal Cost { get { return cost; } }
    public decimal Tax { get { return tax; } }
    public YourType(decimal cost, decimal tax) {
        this.cost = cost;
        this.tax = tax;
    }
}

With:

List<YourType> list = new List<YourType>();
like image 165
Marc Gravell Avatar answered Aug 06 '26 04:08

Marc Gravell


Perhaps the number of items in the second dimension is fixed, or at least, is predictable, so if you're using Microsoft .NET Framework 4.0, you can use a list of tuples:

List<Tuple<double, double>> list = new List<Tuple<int, int>>();

// In your loop...
list.Add(Tuple.Create(cost, tax));

// ... later when retrieving some tuple...
int item0cost = list[0].Item1;
int item0tax = list[0].Item2;

You can always implement some kind of value object class which has Cost and Tax properties, but using tuples you can do it as easy as I shown you in my code sample.

like image 45
Matías Fidemraizer Avatar answered Aug 06 '26 03:08

Matías Fidemraizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!