How to create a dictionary in C#

3 Answers

0 votes
using System;
using System.Collections.Generic;
    
class Program
{
    static void Main() {
        IDictionary<int, string> dict = new Dictionary<int, string>();
         
        dict.Add(1, "c#"); 
        dict.Add(15, "vb.net");
        dict.Add(7, "java");
        dict.Add(2, "python");
 
        foreach(KeyValuePair<int, string> keyval in dict) {
            Console.WriteLine("Key: {0} Value: {1}", keyval.Key, keyval.Value);
        }
    }
}
    
    
    
    
/*
run:
    
Key: 1 Value: c#
Key: 15 Value: vb.net
Key: 7 Value: java
Key: 2 Value: python
    
*/

 



answered Jan 2, 2022 by avibootz
edited Apr 12, 2024 by avibootz
0 votes
using System;
using System.Collections.Generic;
    
class Program
{
    static void Main() {
         
        var dict = new Dictionary<int, string>() { {1, "c#"},
                                                   {15, "c"},
                                                   {7, "java"},
                                                   {2, "python"}
        };
         
        foreach(var keyval in dict) {
            Console.WriteLine("Key: {0} Value: {1}", keyval.Key, keyval.Value);
        }
    }
}
    
    
    
    
/*
run:
    
Key: 1 Value: c#
Key: 15 Value: c
Key: 7 Value: java
Key: 2 Value: python
    
*/

 



answered Jan 2, 2022 by avibootz
edited Apr 12, 2024 by avibootz
0 votes
using System;
using System.Collections.Generic;
    
class Program
{
    static void Main() {
         
        Dictionary<int, int> dic = new Dictionary<int, int>();
 
        dic.Add(1, 555);
        dic.Add(3, 999);
        dic.Add(6, 777);
        dic.Add(9, 888);
 
        foreach (KeyValuePair<int, int> pair in dic) {
            Console.WriteLine("{0} - {1}", pair.Key, pair.Value);
        }
    }
}
    
    
    
    
/*
run:
    
1 - 555
3 - 999
6 - 777
9 - 888
    
*/

 



answered Apr 12, 2024 by avibootz

Related questions

2 answers 119 views
1 answer 120 views
120 views asked Dec 10, 2022 by avibootz
1 answer 161 views
1 answer 529 views
1 answer 178 views
1 answer 166 views
...