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

后端 未结 9 1082
悲&欢浪女
悲&欢浪女 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:21

    You can declare a class that stores both values and then use an ordinary dictionary. For example:

    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});
    
    0 讨论(0)
  • 2020-12-31 12:24

    Create a structure to store your values:

    struct ValuePair
    {
        public ulong Value1;
        public ulong Value2;
    }
    

    Dictionary initialization:

    Dictionary<int, ValuePair> dictionary = new Dictionary<int, ValuePair>();
    

    Maybe List is enough, if you use int as key?

    List:

    List<ValuePair> list = new List<ValuePair>();
    

    ValuePair can be added to the list as following:

    list.Add(new ValuePair { Value1 = 1, Value2 = 2 });
    
    0 讨论(0)
  • 2020-12-31 12:29

    I'm not sure I understand your question correctly, but if you want to store more than one value in the value part of Dictionary, you could do something like this:

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

    You can use insert into the dictionary like this:

    dic.Add(42, new KeyValuePair<ulong, ulong>(42, 42));
    dic.Add(43, new KeyValuePair<ulong, ulong>(43, 43));
    

    And fetch the values like so:

    foreach (var a in dic)
    {
        Console.WriteLine("Key: {0}, Value1: {1}, Value2: {2}",
            a.Key, a.Value.Key, a.Value.Value);
    }
    
    0 讨论(0)
提交回复
热议问题