C#中的文字散列?

时间:2020-03-05 18:50:12  来源:igfitidea点击:

我已经做了cfor很长时间了,从来没有遇到过简单的方法来创建哈希。

我最近熟悉了哈希和Ruby的Ruby语法,有谁知道一种简单的方法将哈希声明为文字,而无需执行所有添加调用。

{ "whatever" => {i => 1}; "and then something else" => {j => 2}};

解决方案

回答

如果我们使用的是C3.0(.NET 3.5),则可以使用集合初始化程序。它们不像Ruby中的那么简洁,但是仍然是一个改进。

本示例基于MSDN示例

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, }}
};

回答

当我无法使用C3.0时,可以使用一个辅助函数,该函数将一组参数转换为字典。

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

像这样使用:

IDictionary<string,object> myDictionary = Dict<string,object>(
    "foo",    50,
    "bar",    100
);

回答

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();                
            Dictionary<object, object > d = p.Dic<object, object>("Age",32,"Height",177,"wrest",36);//(un)comment
            //Dictionary<object, object> d = p.Dic<object, object>();//(un)comment

            foreach(object o in d)
            {
                Console.WriteLine(" {0}",o.ToString());
            }
            Console.ReadLine();    
        }

        public Dictionary<K, V> Dic<K, V>(params object[] data)
        {               
            //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null;
            if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary<K,V>(1){{ (K)new Object(), (V)new object()}};

            Dictionary<K, V> dc = new Dictionary<K, V>(data.Length / 2);
            int i = 0;
            while (i < data.Length)
            {
                dc.Add((K)data[i], (V)data[++i]);
                i++;    
            }
            return dc;            
        }
    }
}