Monday 17 December 2012

c sharp programming

THE GENERIC KEYVALUEPAIR CLASS
C# provides a small class that allows you to create dictionary-like objects that
store data based on a key. This class is called the KeyValuePair class. Each
object can only hold one key and one value, so its use is limited.
A KeyValuePair object is instantiated like this:
KeyValuePair<string, int> mcmillan =
new KeyValuePair<string, int>("McMillan", 99);
The key and the value are retrieved individually:
Console.Write(mcmillan.Key);
Console.Write(""+ mcmillan.Value);


The KeyValuePair class is better used if you put the objects in an array. The
following program demonstrates how a simple grade book might be imple-
mented:

using System;
using System.Collections.Generic;
using System.Text;
namespace Generics
{
class Program
{
static void Main(string[] args)

{
KeyValuePair<string, int>[] gradeBook = new
KeyValuePair<string, int>[10];
gradeBook[0] = new KeyValuePair<string,
int>("McMillan", 99);
gradeBook[1] = new KeyValuePair<string,
int>("Ruff", 64);
for (inti=0;i<= gradeBook.GetUpperBound(0); i++)
if (gradeBook[i].Value != 0)
Console.WriteLine(gradeBook[i].Key + ": " +
gradeBook[i].Value);
Console.Read();
}
}

}

No comments:

Post a Comment