Sorted Dictionary C# 2.0






1.44/5 (9 votes)
Mar 6, 2006

60566

331
Using the SortedDictionary for a contact list.
Introduction
This article is an attempt to add the C# 2.0 SortedDictionary
logic to the article by Liong Ng: XML Serialization in .NET. A portion of the original article is deleted for ease of analysis. I only load data from a tab delimited file and process this data.
Background
I find very little on implementing, and through this article, hope to start a dialogue on, the use of generics and SortedDictionary
. The impetus was for a class project.
Using the code
The Person
, PhoneNumber
, and Contact
classes are all basically as developed in the cited article. The Contacts
class is where most of the changes have been made. We start by loading in firstName
, lastName
, and phoneNumber
from a tab delimited file "ContactList.tsv".
class Contacts
{
// Encapsulate table
private SortedDictionary<Person, Contact> table =
new SortedDictionary<Person, Contact>();
public SortedDictionary<Person, Contact> Table
{
get { return table; }
set { table = value; }
}
....
}
private static SortedDictionary<Person, Contact>
AddEntry(SortedDictionary<Person, Contact> Table)
{
if (File.Exists("ContactList.tsv"))
{
// Open File
StreamReader re = File.OpenText("ContactList.tsv");
.....
if (Table.ContainsKey(person))
{
// show names that have duplicate last name
Console.WriteLine("Person Exists " + person.ToString());
}
else
// add new contact with person as key
Table.Add(Person, Contact);
}
......
}
The display of the contact list uses a foreach
to loop through the table.
// display dictionary content
private static void DisplayDictionary<Person, Contact>
(SortedDictionary<Person, Contact> Table)
{
// Several ways to write data are ahown
// generate output for each key in the sorted dictionary
// by iterating through the Keys property with a foreach statement
foreach (KeyValuePair<Person, Contact> kvp in Table)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach (object de in Table) //DictionaryEntry
{
Console.WriteLine(de.ToString());
}
ICollection valueColl = Table.Values;
foreach (object val in valueColl)
{
//Console.WriteLine("Value = {0}", val);
Console.WriteLine(val);
}
foreach (Person key in Table.Keys)
{
Console.WriteLine(key.ToString());
}
Points of Interest
I made several attempts to get foreach
to work correctly. I would appreciate any and all constructive comments. This is my first project in C#.
History
- Version 1.0 - 3/4/06.