Chapter 9. Collection Classes

In the preceding two chapters we saw how to store information in arrays and lists, and how to sort, search, and process that information using LINQ. Important as sequential lists and rectangular arrays are, they don’t accommodate every possible requirement you could have for storing and structuring data. So in this final chapter on working with collections, we’ll look at some of the other collection classes offered by the .NET Framework.

Dictionaries

A dictionary is a collection that enables you to look up information associated with some kind of value. .NET calls this sort of collection a dictionary because it is reminiscent of a traditional printed dictionary: the information is structured to make it easy to find the entry for a particular word—if you know what word you’re looking for, you can find it very quickly even among tens of thousands of definitions. The information you find when you’ve looked up the word depends on the sort of dictionary you bought—it might provide a definition of the word, but other kinds exist, such as dictionaries of quotations, or of etymology.

Likewise, a .NET dictionary collection is structured to enable quick and easy lookup of entries. The syntax looks very similar to array access, but where you’d expect to see a number, the index can be something else, such as a string, as shown in Example 9-1.

Example 9-1. Looking up an entry in a dictionary

string definition = myDictionary["sea"];

Just as printed dictionaries vary in ...

Get Programming C# 4.0, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.