Mago Maverick Mago Maverick - 1 year ago 60
PHP Question

php arrays simplicity in c#

I worked with php and I make very huge use of his dinamyc arrays.

Now I'm working with c# and I'm searching something similar.

This is the point:

I make a query in a Database and it return me a recordset with 5 fields:

  • Name person

  • date

  • type shift

  • number of shift

  • minutes of work

I want to create on the fly an multidimensional array like this

in $rs I have one record of my recordset

arrWork = array();

arrWork[$rs["Name"]][$rs["Date_shift"]][$rs["type_shift"][$rs["shift"]] += rs["minute_work"];

As you know in 1 line I create all dimension of array.

in c# I have to do this with Hashtables, but I have to check every level, and I think is very time expensive to manage this.

Is there any way to have simplicity of php arrays in c#

Answer Source

Alot of C# programmers actually like the declarative syntax and type-safety of the language. I don't think there's an answer that will completely satisfy your needs.

I gave it a shot though :)

public class ValueOrDictionary : IDictionary<object, ValueOrDictionary>
    private readonly IDictionary<object, ValueOrDictionary> storage = new Dictionary<object, ValueOrDictionary>();
    private object value;
    private bool isValue = false;

    public ValueOrDictionary this[object key]
            if (isValue)
                throw new InvalidOperationException();

            ValueOrDictionary subLevel;
            if (!storage.TryGetValue(key, out subLevel))
                subLevel = new ValueOrDictionary();
                storage[key] = subLevel;

            return subLevel;
            storage[key] = value;

    public object Value
            return value;
            this.value = value;
            isValue = value != null;

    // ... rest of IDictionary<,> implementation

You could then use this as below:

ValueOrDictionary arr = new ValueOrDictionary();
arr["a"]["b"].Value = 8;
int myvalue = (int)arr["a"]["b"].Value;

This way each "level" in the dictionary doubles as a "value container".

In the end you may win some time when first writing your application, but I think you'll spend alot more time maintaining the application because your compiler can no longer help you determine the type of each value.

It would also be alot harder getting help with your phpc# code from your colleagues or here on SO, if you hang on to what you're currently used to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download