如何在C#中将字典初始化为(键,值,值)对

Roy*_*son 11 .net c# dictionary

我想将值存储为键,值,值对.我的数据类型

Key -> int & both values -> ulong,
Run Code Online (Sandbox Code Playgroud)

如何初始化和获取此类字典的值.我正在使用VS-2005.

如果我使用类或结构,那么我如何获取值.

bni*_*dyc 17

创建一个存储值的结构:

struct ValuePair
{
    public ulong Value1;
    public ulong Value2;
}
Run Code Online (Sandbox Code Playgroud)

字典初始化:

Dictionary<int, ValuePair> dictionary = new Dictionary<int, ValuePair>();
Run Code Online (Sandbox Code Playgroud)

如果你使用int作为密钥,也许List就足够了?

列表:

List<ValuePair> list = new List<ValuePair>();
Run Code Online (Sandbox Code Playgroud)

ValuePair可以添加到list以下内容:

list.Add(new ValuePair { Value1 = 1, Value2 = 2 });
Run Code Online (Sandbox Code Playgroud)


Kon*_*man 14

您可以声明一个存储两个值的类,然后使用普通字典.例如:

class Values {
    ulong Value1 {get;set;}
    ulong Value2 {get;set;}
}

var theDictionary=new Dictionary<int, Values>;

theDictionary.Add(1, new Values {Value1=2, Value2=3});
Run Code Online (Sandbox Code Playgroud)

  • 您可以将Values设为结构. (4认同)
  • 两个ulongs是16个字节,所以是的,这是结构合适的罕见情况之一.对于KeyValuePair,我不会使用它,除非*实际上*这两个值是一个键和一个值,以使代码更容易理解. (4认同)
  • 最好使用KeyValuePair而不是自定义类,或者至少使用struct. (2认同)

nas*_*ski 9

这是一个选择:

Dictionary<int, KeyValuePair<ulong, ulong>> dictionary = new Dictionary<int, KeyValuePair<ulong, ulong>>();
Run Code Online (Sandbox Code Playgroud)

如果要添加值:Key = 1,Pair = {2,3}

dictionary.Add(1, new KeyValuePair<ulong, ulong>(2, 3));
Run Code Online (Sandbox Code Playgroud)

如果要检索这些值:

var valuePair = dictionary[1];
ulong value1 = valuePair.Key;
ulong value2 = valuePair.Value;
Run Code Online (Sandbox Code Playgroud)

或者干脆:

ulong value1 = dictionary[1].Key;
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢Konamiman的方法,因为它更干净,但这将没有新的课程. (2认同)
  • 从语义上讲,“ KeyValuePair”由一个* key *和一个* value *组成。OP希望存储*两个值*,因此尽管`KeyValuePair`可以解决问题,但这并不是一个很好的“语义”匹配方式。 (2认同)

Mar*_*dle 6

在System命名空间中创建一个Tuple类:

public class Tuple<T1,T2>
{
    private readonly T1 _item1;
    private readonly T2 _item2;

    public Tuple(T1 item1, T2 item2)
    {
        this._item1 = item1;
        this._item2 = item2;
    }

    public T1 Item1 { get { return _item1; } }

    public T2 Item2 { get { return _item2; } }
}
Run Code Online (Sandbox Code Playgroud)

还有一个带有Create方法的静态Tuple类,因此您可以获得构造函数中不可用的类型推断:

public static class Tuple
{
    public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
    {
        return new Tuple<T1, T2>(item1, item2);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当你进入.NET 4.0时,你可以删除这些类,因为它们在基类库中(并且与F#元组兼容!).