Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Store Mixed Array Data?

Tags:

arrays

c#

types

Let's say I have an array I need to store string values as well as double values. I know I can store the doubles as strings, and just deal with the conversions, but is it possible to use an array with two data types?

like image 408
sooprise Avatar asked Sep 07 '10 19:09

sooprise


People also ask

How do you store multiple data types in an array?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

Can an array store different data types in C?

Array is a derived data type which is used to store the data of the same type in a contiguous memory location. We can store any type of data types ranging from int , float, double, char to pointer, string, structure.

Can we store a string and integer together in an array If I can't and I want to what should I do?

You can use a Map data structure instead of an array. This is basically a type of Collection that has key-value pairs. Your string name can be used as the key and the value is your integer. Map<String,Integer> myMap = new HashMap<String, Integer>; MyMap.

What data type could be used to store a number in an array?

The values in an array can be any type, so that arrays may contain values that are simple reals or integers, vectors, matrices, or other arrays. Arrays are the only way to store sequences of integers, and some functions in Stan, such as discrete distributions, require integer arguments.


1 Answers

You may use object[] and do some type checking. You will get some boxing/unboxing when accessing the doubles, but that will be faster than double.Parse() anyway.

An alternative is to create a class with both types and a marker:

class StringOrDouble
{
    private double d;
    private string s;
    private bool isString;

    StringOrDouble(double d)
    {
        this.d = d;
        isString = false;
    }

    StringOrDouble(string s)
    {
        this.s = s;
        isString = true;
    }

    double D
    {
        get
        {
            if (isString)
                throw new InvalidOperationException("this is a string");
            return d;
        }
    }

    string S
    {
        get
        {
            if (!isString)
                throw new InvalidOperationException("this is a double");
            return s;
        }
    }
    bool IsString { get { return isString; } }
}

and then create an array of StringOrDouble. This will save you from some typechecking and boxing, but will have a larger memory overhead.

like image 64
Albin Sunnanbo Avatar answered Sep 21 '22 07:09

Albin Sunnanbo