Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Collection Initializers and Query Expressions for Dictionary Objects

0.00/5 (No votes)
12 Feb 2009 1  
This article explains the syntax to use collection initializers and query expressions for Dictionary objects in C# 3.0.

Introduction

This article explains the syntax to use collection initializers and query expressions for Dictionary objects in C# 3.0.

Background 

I was learning the new features of C# 3.0. Though the use of collection initializers and query expressions are simple and straight forward in most cases, their use with Dictionary objects are not well documented. Hence, this article gives a beginner level approach to understanding collection initializers and query expressions with Dictionary objects.

Using the Code

In the below block of code, a Dictionary object (currencyCollection) has been defined. The Key holds an id, and the Value holds different currencies.

//Collection Initializers
Dictionary<int, string> currencyCollection = new Dictionary<int, string> {
                {1,"Indian Rupee"},
                {2, "United States Dollar"},
                {3, "Euro"},
                {4, "British Pound"},
                {5, "Australian Dollar"},
                {6, "Japanese Yen" },
                {7,"Indian Rupee"}
};

In the next step, I'm querying the currency "Indian Rupee" using query expressions. This expression will find out the entries for "Indian Rupee".

//Query Expressions
var query = from c in currencyCollection
            where (c.Value.Equals("Indian Rupee"))
            select c;

Now the variant query has the objects after filtering only "Indian Rupee". I use a simple foreach to display the results.

//Iterate through the dictionary and print
foreach (var ky in query)
    Console.WriteLine("{0}, {1}", ky.Key.ToString(), ky.Value); 

Points of Interest

Two things which I learnt were as follows:

  1. How to use collection initializers for Dictionary objects.
  2. How to use query expressions for Dictionary objects.

History

  • Created: 2009-Feb-11

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here