C# Equivalent to PHP Associative Array

c# array like PHP

Beside the answer posted by Enigmativity which is more like as PHP code, the following code shows using object-properties to achieve similar structs which could be simpler than using those nested Dictionary<string, Dictionary<string, string ... in some situations:

var price_changes = new { 
color = new { Red = "2", Blue = "-10%" },
size = new { Large = 1, Medium = -3 }
};

Usage is so easy:

var x = price_changes.size.Large;

What is the easiest way to handle associative array in c#?

Use the Dictionary class. It should do what you need.
Reference is here.

So you can do something like this:

IDictionary<string, int> dict = new Dictionary<string, int>();
dict["red"] = 10;
dict["blue"] = 20;

C# mimic associative array of unknown key-number (like in PHP)

C# is strongly typed so it seems not easy to replicate this exact behavior.

A "possibility" :

public class UglyThing<K,E>
{
private Dictionary<K, UglyThing<K, E>> dicdic = new Dictionary<K, UglyThing<K, E>>();

public UglyThing<K, E> this[K key]
{
get
{
if (!this.dicdic.ContainsKey(key)) { this.dicdic[key] = new UglyThing<K, E>(); }
return this.dicdic[key];
}
set
{
this.dicdic[key] = value;
}
}

public E Value { get; set; }
}

Usage :

        var x = new UglyThing<string, int>();

x["a"].Value = 1;
x["b"].Value = 11;
x["a"]["b"].Value = 2;
x["a"]["b"]["c1"].Value = 3;
x["a"]["b"]["c2"].Value = 4;

System.Diagnostics.Debug.WriteLine(x["a"].Value); // 1
System.Diagnostics.Debug.WriteLine(x["b"].Value); // 11
System.Diagnostics.Debug.WriteLine(x["a"]["b"].Value); // 2
System.Diagnostics.Debug.WriteLine(x["a"]["b"]["c1"].Value); // 3
System.Diagnostics.Debug.WriteLine(x["a"]["b"]["c2"].Value); // 4

Multidimensional Associative Arrays in C#

Your current PHP code is like this:

$roomDiscount["apartment"][0]["minDaysOfStay"] = 10;

It is close to this kind of structure in C#:

Dictionary<string, List<Dictionary<string, double>>>

Declaring such an object probably isn't a good way of going about it. Instead you should define class objects instead. The example I give below is for illustrative purposes only, and isn't necessarily the best way to do this (there are many different approaches to this situation):

public class RoomDiscount
{
public int MinDaysOfStay {get;set;}
public double Discount {get;set;}
}

public class RoomDiscounts
{
public List<RoomDiscount> DiscountBands {get;set;}
}

Usage:

Dictionary<string, RoomDiscounts> discountDetails = new Dictionary<string, RoomDiscounts>();
discountDetails["apartment"] = new RoomDiscounts {
DiscountBands = new List<RoomDiscount> {
new RoomDiscount {
MinDaysOfStay = 10,
Discount = 0.3
},
new RoomDiscount {
MinDaysOfStay = 15,
Discount = 0.35
},
new RoomDiscount {
MinDaysOfStay = 16,
Discount = 0.5
}
}
};

string room = "apartment";
int daysOfStay = 26;
double discount = discountDetails[room].DiscountBands.OrderByDescending(b => b.MinDaysOfStay).FirstOrDefault(b => daysOfStay >= b.MinDaysOfStay)?.Discount ?? 0;

Again, this is just an example of one way you could organise your data in a more strongly-typed fashion. Note that this will throw an exception if the room type isn't defined, so you could use TryGetValue to retrieve the details from the dictionary.

Is there a C# equivalent of PHP's array_key_exists?

Sorry, but dynamic arrays like PHP are not supported in C#. What you can do it create a Dictionary<TKey, TValue>(int, int) and add using .Add(int, int)

using System.Collections.Generic;
...
Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(5, 4);
dict.Add(7, 8);
if (dict.ContainsKey(5))
{
// [5, int] exists
int outval = dict[5];
// outval now contains 4
}

Associative array in an another array c#

In C# an associative array would be a Dictionary. Since you have two dimensions, that's a dictionary or dictionaries:

var myarr = new Dictionary<int, Dictionary<string, string>>();
int x = 5;

myarr[x] = new Dictionary<string, string>();
myarr[x]["date1"] = "text";
myarr[x]["date2"] = "text";

Of course an associative array where the key is an integer, the keys start at 0, and are contiguous, would be represented as a C# array or List, so if your integer keys meet those constraints, then you may want to have a List<Dictionary<string, string>>.



Related Topics



Leave a reply



Submit