how to initialize dictionary as (key,value,value) pair in C#

后端 未结 9 1081
悲&欢浪女
悲&欢浪女 2020-12-31 11:37

I want to store values as key,value,value pair. My data is of type

Key -> int & both values -> ulong,

How to initialize & fet

相关标签:
9条回答
  • 2020-12-31 12:09

    In C# 4, you'll have the Tuple type for your value, value pair.

    There's an MSDN article describing the type and the design decisions behind it.

    0 讨论(0)
  • 2020-12-31 12:11

    maybe you have to define a class say class Pair to hold your two value, and use int as the key.

    0 讨论(0)
  • 2020-12-31 12:14

    This would be an option:

    Dictionary<int, KeyValuePair<ulong, ulong>> dictionary = new Dictionary<int, KeyValuePair<ulong, ulong>>();
    

    If you want to add in a value: Key=1, Pair = {2,3}

    dictionary.Add(1, new KeyValuePair<ulong, ulong>(2, 3));
    

    If you want to retrieve those values:

    var valuePair = dictionary[1];
    ulong value1 = valuePair.Key;
    ulong value2 = valuePair.Value;
    

    Or simply:

    ulong value1 = dictionary[1].Key;
    
    0 讨论(0)
  • 2020-12-31 12:16

    Look at Wintellect.PowerCollections Namespace they have special structure Pair<(Of ) and collections to work with it or you'll need to code your own Pair type.

    0 讨论(0)
  • 2020-12-31 12:17

    Create a Tuple class, in the System namespace:

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

    And a static Tuple class with a Create method so you get type inference which is not available on constructors:

    public static class Tuple
    {
        public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
        {
            return new Tuple<T1, T2>(item1, item2);
        }
    }
    

    Then, when you get onto .NET 4.0, you can delete these classes because they're in the Base Class Library (and are compatible with F# tuples!).

    0 讨论(0)
  • 2020-12-31 12:20

    You can make use of the KeyValuePair

    Dictionary<int, KeyValuePair<ulong,ulong>> vals = new Dictionary<int, KeyValuePair<ulong, ulong>>();
    
    0 讨论(0)
提交回复
热议问题