Pages

Saturday, June 2, 2012

to get dictionary object values one by one?

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary dictionary =
            new Dictionary();
        dictionary.Add("cat", 2);
        dictionary.Add("dog", 1);
        dictionary.Add("llama", 0);
        dictionary.Add("iguana", -1);
    }
}

If you want look up

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary dictionary = new Dictionary();
        dictionary.Add("apple", 1);
        dictionary.Add("windows", 5);

        // See whether Dictionary contains this string.
        if (dictionary.ContainsKey("apple"))
        {
            int value = dictionary["apple"];
            Console.WriteLine(value);
        }

        // See whether Dictionary contains this string.
        if (!dictionary.ContainsKey("acorn"))
        {
            Console.WriteLine(false);
        }
    }
}


using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Example Dictionary again
        Dictionary d = new Dictionary()
        {
            {"cat", 2},
            {"dog", 1},
            {"llama", 0},
            {"iguana", -1}
        };
        // Loop over pairs with foreach
        foreach (KeyValuePair pair in d)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
        // Use var keyword to enumerate dictionary
        foreach (var pair in d)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
    }
}

No comments:

Post a Comment