Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal hashes in c#?

I've been doing c# for a long time, and have never come across an easy way to just new up a hash.

I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.

{ "whatever" => {i => 1}; "and then something else" => {j => 2}};
like image 998
DevelopingChris Avatar asked Sep 09 '08 17:09

DevelopingChris


3 Answers

If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.

This example is based on the MSDN Example

var students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}
};
like image 158
Wheelie Avatar answered Nov 04 '22 22:11

Wheelie


When I'm not able to use C# 3.0, I use a helper function that translates a set of parameters into a dictionary.

public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data)
{
    Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2));
    if (data == null || data.Length == 0) return dict;

    KeyType key = default(KeyType);
    ValueType value = default(ValueType);

    for (int i = 0; i < data.Length; i++)
    {
        if (i % 2 == 0)
            key = (KeyType) data[i];
        else
        {
            value = (ValueType) data[i];
            dict.Add(key, value);
        }
    }

    return dict;
}

Use like this:

IDictionary<string,object> myDictionary = Dict<string,object>(
    "foo",    50,
    "bar",    100
);
like image 36
Matt Avatar answered Nov 05 '22 00:11

Matt


Since C# 3.0 (.NET 3.5) hashtable literals can be specified like so:

var ht = new Hashtable {
    { "whatever", new Hashtable {
            {"i", 1} 
    } },
    { "and then something else", new Hashtable { 
            {"j",  2}
    } }
};
like image 1
Matthew Lock Avatar answered Nov 04 '22 22:11

Matthew Lock