简体   繁体   中英

What is the standard equivalent of Ruby Hash in C# - How to create a multi dimensional Ruby like hash in C#

I have prior experience in Ruby and wanted to learn a compiled language and have just picked up C# recently. I am wondering what is the Ruby Equivalent of Hashes in C#. Eg, how can i create a something similar to a Ruby hash below, in C#?

x = {"a"=>{"b"=>"c","d"=>["e","f",{"g"=>1}]}

What is the standard way to create something like this in C#? Should I use hashtable, dictionary or objects?

Short answer: There is none.

Long answer:

The closest C# equivalent is the Dictionary .

You can use it like so:

var myDict = new Dictionary<string, int>();

// Adding values
myDict.Add("foo", 3);
myDict["bar"] = 8; // Alternative syntax

// Getting values
int bar =  myDict["bar"];
bool fooExists = myDict.ContainsKey("foo"); // true

// Safe get
int foo;
bool ableToGetFoo = myDict.TryGetValue("foo", out foo);

// Splitting
var allKeys = myDict.Keys;
var allValues = myDict.Values;

However, this would not work for you . At least, not in any straightforward way.

You have to realize that C# is a strongly typed language. This means that C#'s dictionaries, like all other collections, have a limitation: all elements must be of the same type. This means that all the keys must be the same type as each other, and all the values must also be the same type as each other. That is simply how strongly typed languages work.

If you want to re-create your example in C#, you'll have to define a custom data structure to accommodate it. However, all the nesting that is present in your example will make that challenging. Some elements of it, such as this particular bit:

["e","f",{"g"=>1}]

..are flat out impossible. An array or list cannot have elements of completely different types.

Here is my attempt at creating something similar to your example:

var x = new Dictionary<string, Dictionary<string, List<string>>>()
{
    {
        "a", new Dictionary<string, List<string>>()
        {
            {"b", ["c"]},
            {"d", ["e", "f", "g"]}
        }
    },
};

EDIT: In order to work with JSON you'd need to take a class based approach. It would look something like this:

public class A
{
    public string b { get; set; }
    public List<object> d { get; set; }
}

public class RootObject
{
    public A a { get; set; }
}

And the corresponding JSON (direct translation from your example):

{
    "a": {
        "b":"c",
        "d":["e", "f", {"g":1}]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM