Thursday, July 31, 2014

CSharp C# Example of Dictionary with List as value

CSharp C# Example of Dictionary with List as value

Overview:

This could come into play where you would like a dictionary grouping of data and use another container, besides a class or Tuple, to hold the data.


This example uses a Dictionary of integers and each Dictionary entry contains from 0 [zero] to n strings.



using System;
using System.Collections.Generic;

namespace ConsoleApplication008
{
    class Program
    {
        private static void Main(string[] args)
        {
            Dictionary<int, List<string>> MyDictionary = new Dictionary<int, List<string>>();
            MyDictionary.Add(0, new List<string>(){"string One"});
            Console.WriteLine("One = {0}", MyDictionary[0][0]);
            MyDictionary[0].Add("string two");
            foreach (string strNow in MyDictionary[0])
            {
                Console.WriteLine(strNow);
            }
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment