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

此生再无相见时 提交于 2020-01-30 08:38:45

问题


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?


回答1:


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}]
    }
}


来源:https://stackoverflow.com/questions/45503442/what-is-the-standard-equivalent-of-ruby-hash-in-c-sharp-how-to-create-a-multi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!