> In this post, we will see how to use a dictionary in C#.
> A dictionary in C# is used to store collection of values with key values as pair.
> So whenever user wants to get the value then he will have to pass the key value to the dictionary and it will return the value to the user.
> The namespace of the C# dictionary is System.Collections.Generic.
> Let’s take a simple example of storing digits from 0 to 9 as key value and these digits in the word form as the collection values.
> Here, the user will type a digit from 0 to 9 and on clicking the button, it gives the digit in the word form.
> To keep this example simple, here the dictionary will be having digits from 0 to 9 only and if user enters a value less than 0 or greater than 9 then he will get the appropriate message.
> Following is the code for demonstrating the use of the Dictionary:
> A dictionary in C# is used to store collection of values with key values as pair.
> So whenever user wants to get the value then he will have to pass the key value to the dictionary and it will return the value to the user.
> The namespace of the C# dictionary is System.Collections.Generic.
> Let’s take a simple example of storing digits from 0 to 9 as key value and these digits in the word form as the collection values.
> Here, the user will type a digit from 0 to 9 and on clicking the button, it gives the digit in the word form.
> To keep this example simple, here the dictionary will be having digits from 0 to 9 only and if user enters a value less than 0 or greater than 9 then he will get the appropriate message.
> Following is the code for demonstrating the use of the Dictionary:
HTML Code:
<body>
<form id="form1" runat="server">
<div>
Enter a number:
<asp:TextBox ID="txtDigit" runat="server"></asp:TextBox>
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" />
</div>
<br />
<div id="output" runat="server"></div>
</form>
</body>
C# code:
//method to get the digit in the word form using the C# dictionary
protected string GetDigitInWord(int digit)
{
string word="Enter a single digit from 0 to 9 only";
//declaring the dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
if (digit >= 0 && digit <= 9)
{
//adding values to dictionary with key
dict.Add(0, "Zero");
dict.Add(1, "One");
dict.Add(2, "Two");
dict.Add(3, "Three");
dict.Add(4, "Four");
dict.Add(5, "Five");
dict.Add(6, "Six");
dict.Add(7, "Seven");
dict.Add(8, "Eight");
dict.Add(9, "Nine");
//getting digit in word by passing digit as key value
word = dict[digit];
}
return word;
}
protected void btnGet_Click(object sender, EventArgs e)
{
int digit = Convert.ToInt32(txtDigit.Text);
//calling above method by passing the entered digit and getting its word form
output.InnerText= this.GetDigitInWord(digit);
}
Output:
Output 1: Entering digit greater than 9 and getting message.
Output 2: Entering 3 as value and getting its word form:
That's it....
Comments
Post a Comment