How to sort DropDownList items in descending order in asp.net


DropDownList items sort order by descending



DropDownList is an asp.net list web server control that allow us to select one item at a time
from a drop-down-list. by default dropdownlist items are not sorted. to provide better user experience, web
developer wants to create a sorted dropdownlist. the following asp.net c# example code demonstrate us how can
we render a dropdownlist server control which items are descending sorted.






DropDownList server control have no built in property or method to sort its items descending or ascending order. we need to
apply few techniques to display a sorted dropdownlist programmatically.






At first we create a generic list which data type is ListItem. now we populate the generic list from dropdownlist
items collection. next we sort the list by descending order using Linq OrderByDescending() extension method. finally we clear the
dropdownlist items, and repopulate the dropdownlist with the sorted generic list. now we can display a descending sorted
dropdownlist on web browser. sorting applied for first page load time only, because we track the postback using page IsPostBack property.




dropdownlist-sort-order-by-descending.aspx



<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//create a generic list data type ListItem
List<ListItem> list = new List<ListItem>();

foreach (ListItem litem in DropDownList1.Items)
{
//add ListItem to generic list
list.Add(litem);
}

//sort list items by item text descending
List<ListItem> sorted = list.OrderByDescending(b => b.Text).ToList();

//clear dropdownlist items
DropDownList1.Items.Clear();

//repopulate dropdownlist with sorted items.
foreach (ListItem litem in sorted)
{
DropDownList1.Items.Add(litem);
}
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net c# dropdownlist sort order by descending</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net c# example - dropdownlist sort order by descending
</h2>
<hr width="550" align="left" color="Gainsboro" />
<br /><br />
<asp:DropDownList
ID="DropDownList1"
runat="server"
AutoPostBack="true"
Width="350"
Font-Size="X-Large"
Font-Names="Comic Sans MS"
>
<asp:ListItem Text="Grey Goshawk" Value="1"></asp:ListItem>
<asp:ListItem Text="African Harrier Hawk" Value="2"></asp:ListItem>
<asp:ListItem Text="Northern Goshawk" Value="3"></asp:ListItem>
<asp:ListItem Text="Common Black Hawk" Value="4"></asp:ListItem>
<asp:ListItem Text="Philippine Eagle" Value="5"></asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>




How to add top margin to a Label in asp.net

Add top margin to a Label control
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can add the top margin to a Label web server control. To add the top margin to a Label control, the asp.net c# developers have to apply a custom CSS style to a Label control. In the below example code, we demonstrate two ways to add the top margin to a Label web server control.

The Label CssClass property gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client. The CssClass property is inherited from WebControl. The CssClass property value is a String which is the CSS class rendered by the Label server control on the client. The default value of this property is Empty.

So using this CssClass property the asp.net c# developers can add only the top margin to a Label control. The asp.net developers just have to set the CSS margin-top style value to a specified pixel value.

There is another way to add the top margin to a Label web server control. The asp.net c# developers have to add a Style property to a Label control where they can use the Style property Add() method to add the margin-top CSS style with a specified pixel value.

The Label Style property gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control. This property is also inherited from WebControl. The Style property value is a CssStyleCollection that contains the HTML style attributes to render on the outer tag of the Web server control.
label-margin-top.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.CssClass = "LabelMarginTopStyle";

        //another way to apply top margin in label control.
        //Label1.Style.Add("margin-top","50px");
    }  
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <style type="text/css">
        .LabelMarginTopStyle {
            margin-top:50px;
        }
    </style>      
    <title>asp.net example - label margin-top</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label margin-top
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="sample label to test label top margin."
            BorderColor="HotPink"
            BorderWidth="1"
            Font-Size="X-Large"
            Width="350"
            >      
        </asp:Label>      
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="label margin-top"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>      
    </form>      
</body>      
</html>

How to add margin to a Label in asp.net

Add margin to a Label
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can add a margin to a Label web server control. To add a margin to a Label control, the asp.net c# developers have to apply a custom CSS style to a Label control.

The Label CssClass property gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client. The CssClass property is inherited from WebControl. The CssClass property value is a String which is the CSS class rendered by the Label server control on the client. The default value of this property is Empty.

So finally, using this CssClass property the asp.net c# developers can add a margin to a Label control. The asp.net developers just have to set the CSS margin style value to a specified pixel value.
label-margin.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.CssClass = "LabelMarginStyle";

        //another way to apply margin in label control.
        //Label1.Style.Add("margin","25px");
    }  
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <style type="text/css">
        .LabelMarginStyle {
            margin:25px;
        }
    </style>      
    <title>asp.net example - label margin</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label margin
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="sample label to test label margin."
            BorderColor="Green"
            BorderWidth="1"
            Font-Size="X-Large"
            Width="350"
            >      
        </asp:Label>      
        <br /><br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="label margin"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>      
    </form>      
</body>      
</html>

How to justify the text in a Label in asp.net

Justify text in a Label control
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can justify the text on a Label web server control. To justify text in a Label control, the asp.net c# developers have to apply a custom CSS style to a Label control.

The Label CssClass property gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client. The CssClass property is inherited from WebControl. The CssClass property value is a String which is the CSS class rendered by the Label server control on the client. The default value of this property is Empty.

So using this CssClass property the asp.net c# developers can justify text in a Label control. The asp.net developers just have to set the CSS text-align style value to justify.

There is another way to justify Label web server control’s text. The asp.net c# developers have to add a Style property to a Label control where they can use the Style property Add() method to add the text-align CSS style with justify value.

The Label Style property gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control. This property is also inherited from WebControl. The Style property value is a CssStyleCollection that contains the HTML style attributes to render on the outer tag of the Web server control.
label-justify-text.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.CssClass = "LabelJustifyTextStyle";

        //another way to apply label justify text.
        //Label1.Style.Add("text-align","justify");
    }  
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <style type="text/css">
        .LabelJustifyTextStyle {
            text-align:justify;
        }
    </style>      
    <title>asp.net example - label justify text</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label justify text
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's..."
            BorderColor="Red"
            BorderWidth="1"
            Font-Size="X-Large"
            Width="350"
            >      
        </asp:Label>      
        <br /><br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="label justify text"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>      
    </form>      
</body>      
</html>

How to trim text with ellipsis in a Label in asp.net

Trim text with ellipsis on a Label
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can trim a text with an ellipsis and display it on a Label web server control. To show an ellipsis on a Label control, the asp.net c# developers have to apply a custom CSS style to a Label control.

The Label CssClass property gets or sets the Cascading Style Sheet (CSS) class rendered by the Web server control on the client. The CssClass property is inherited from WebControl. The CssClass property value is a String which is the CSS class rendered by the Label server control on the client. The default value of this property is Empty.

So finally, using this CssClass property the asp.net c# developers can make a Label control’s long text trimmed and display an ellipsis at the end of the text. The asp.net developers just have to set the CSS text-overflow style value to ellipsis. Here we also applied the display CSS style value to block, the white-space value to nowrap, and the overflow value to hidden.
label-ellipsis.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.CssClass = "LabelEllipsisStyle";
    }  
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <style type="text/css">
        .LabelEllipsisStyle {
            text-overflow:ellipsis;
            white-space:nowrap;
            display:block;
            overflow:hidden;
        }
    </style>      
    <title>asp.net example - label ellipsis</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label ellipsis
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="sample label to test label ellipsis."
            BorderColor="Red"
            BorderWidth="1"
            Font-Size="X-Large"
            Width="250"
            ToolTip="sample label to test label ellipsis."
            >      
        </asp:Label>      
        <br /><br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="label ellipsis"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>      
    </form>      
</body>      
</html>

How to display html tags in a Label in asp.net

Show HTML tags on a Label
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can display HTML tags in a Label web server control. To show HTML tags on a Label control, the asp.net c# developers have to encode HTML tags.

The Server HTMLEncode() method applies HTML encoding to a specified string. The HTMLEncode() method is very useful and a quick method of encoding form data and other client request data before using it in a Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

The Server HTMLEncode() method has a parameter named string which specifies the string to encode. The Server HTMLEncode() method has no return values.
label-display-html.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Label1.Text = Server.HtmlEncode("<form id='form1' runat='server'>");
        Label1.Text += "<br />";
        Label1.Text += Server.HtmlEncode("<title>asp.net example - label display html</title>");
    }  
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>asp.net example - label display html</title>
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label display html
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Text="sample label to display html."
            Font-Size="X-Large"
            >      
        </asp:Label>      
        <br /><br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="label display html"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>      
    </form>      
</body>      
</html>

How to add an onClick event to a Label in asp.net

Add an onClick event to a Label
The Label class Represents a label control, which displays text on a Web page. The asp.net developers can use the Label control to display text in a set location on the web page. Unlike static text, asp.net c# developers can customize the displayed text through the Text property.

The following asp.net c# tutorial code demonstrates how we can add an onClick event to a Label web server control. But there is no built-in onClick event in the Label control. So we have to find an alternate solution to attach a click event to a Label control.

In the below asp.net c# code, we used the Label control’s Attributes property to add a click event to a Label web server control. The Attributes property allows us to add a javascript click event to a Label server control.

The Label Attributes property gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control. This property is inherited from WebControl. The Attributes property value is an AttributeCollection of name and value pairs.

So finally, using this Attributes property the asp.net developers can add a javascript onClick event to the Label control. In this example code, we showed an alert on the web browser when someone clicks the Label control.
test.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        Label1.Attributes.Add("OnClick", "javascript:alert('label clicked.')");
    }    
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>asp.net example - label onclick</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            asp.net example - label onclick
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="XX-Large"
            Text="Click Here To Test Label OnClick Event."    
            >      
        </asp:Label>      
    </div>      
    </form>      
</body>      
</html>

c# - How to convert a Dictionary to a string

Dictionary to string
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object structure is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can convert a Dictionary object to a String object. To achieve this, we initially initialize an instance of an empty Dictionary object. Whose key and value data types both are String. Then we add elements (key-value pair) to the Dictionary instance. We can display the Dictionary elements on the screen (ap.net page) using a foreach loop.

We initialize an empty StringBuilder object. StringBuilder object represents a mutable string of characters. We can add text to the StringBuilder using its Append() method. So we loop through the Dictionary elements and append its keys and values to the StringBuilder. Finally, we convert the StringBuilder to a String object using the ToString() method. The converted String object holds the Dictionary elements keys and values text.
dictionary-to-string.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>

<script runat="server">    
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //initialize a dictionary with keys and values.  
        Dictionary<int, string> birds = new Dictionary<int, string>() {  
            {1,"White Stork"},  
            {2,"Jabiru"},  
            {3,"Marabou Stork"},  
            {4,"Scarlet Ibis"}  
        };

        Label1.Text = "dictionary elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //create a stringbuilder.
        StringBuilder sb = new StringBuilder();

        //append dictionary key value to stringbuilder.
        foreach (KeyValuePair<int, string> pair in birds)
        {
            sb.Append(pair.Key);
            sb.Append("[");
            sb.Append(pair.Value);
            sb.Append("]");
            sb.Append(",");
        }

        Label1.Text += "<br /><br />dictionary elements to string.....<br />";
        Label1.Text += sb.ToString().TrimEnd(',');
    }      
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - dictionary to string</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - dictionary to string
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="Large"    
            >      
        </asp:Label>      
        <br /><br />    
        <asp:Button       
            ID="Button1"       
            runat="server"       
            Text="dictionary to string"      
            OnClick="Button1_Click"    
            Height="40"      
            Font-Bold="true"      
            />      
    </div>      
    </form>      
</body>      
</html>

c# - How to reverse a Dictionary items

Dictionary reverse
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can reverse the Dictionary element’s position. By default a Dictionary position its elements as they were added to the collection. But the .net developers can reverse the Dictionary elements position using the .net c# built-in method.

The Enumerable Reverse() method inverts the order of the elements in a sequence. The Enumerable Reverse() method returns a sequence whose elements correspond to those of the input sequence in reverse order.

The Enumerable ToDictionary() method creates a Dictionary<TKey,TValue> object from an IEnumerable<T>.The Enumerable Reverse() and the ToDictionary() methods both exist in System.Linq namespace.

Finally, we can reverse the Dictionary element's order using the Enumerable Reverse() method, and then we can convert the return sequence to a Dictionary using the Enumerable ToDictionary() method. As an example, after reversing Dictionary elements order it holds the last element first and the first element last, and so on.
dictionary-reverse.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>      
<script runat="server">    
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //initialize a dictionary with keys and values.  
        Dictionary<int, string> birds = new Dictionary<int, string>() {  
            {1,"Antarctic Petrel"},  
            {2,"Northern Fulmar"},  
            {3,"Southern Giant Petrel"},  
            {4,"Antarctic Prion"},  
            {5,"Cape Petrel"}  
        };

        Label1.Text = "dictionary elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //reverse the elements of dictionary.
        birds = birds.Reverse().ToDictionary(x=>x.Key,x=>x.Value);

        Label1.Text += "<br /><br />dictionary after reverse elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }      
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - dictionary reverse</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - dictionary reverse
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="Large"    
            >      
        </asp:Label>      
        <br /><br />    
        <asp:Button       
            ID="Button1"       
            runat="server"       
            Text="dictionary reverse"      
            OnClick="Button1_Click"    
            Height="40"      
            Font-Bold="true"      
            />      
    </div>      
    </form>      
</body>      
</html>

c# - How to find duplicate values from a Dictionary

Find duplicate values from a dictionary
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method. We also can add some items to the Dictionary at the initializing time.

The following .net c# tutorial code demonstrates how we can find duplicate values from a Dictionary. Dictionary keys are unique, we can’t put multiple elements in a Dictionary with the same key. But Dictionary values can be duplicated. The .net developers can set the same value to multiple elements. So, sometimes the .net developers need to find the duplicate values from a Dictionary items collection.

To find the duplicate values from a Dictionary object, we have to group Dictionary items whose value exists more than one time. The Enumerable GroupBy() method groups the elements of a sequence.

In this expression, we applied a condition while grouping Dictionary items. The condition is value exists more than one time. Finally, we get the Dictionary duplicate values using GroupBy() method and we can loop through the filtered items collection to display it on the user interface.
dictionary-find-duplicate-values.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>  

<!DOCTYPE html>      
<script runat="server">    
    protected void Button1_Click(object sender, System.EventArgs e)  
    {  
        //initialize a dictionary with keys and values.  
        Dictionary<int, string> birds = new Dictionary<int, string>() {  
            {1,"Golden Pheasant"},  
            {2,"Southern Screamer"},  
            {3,"Golden Pheasant"},  
            {4,"Swan Goose"},  
            {5,"Swan Goose"},  
            {6,"Golden Pheasant"},  
            {7,"Greylag Goose"}  
        };

        Label1.Text = "dictionary elements..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //get dictionary duplicate values.
        var duplicatesValue = birds.GroupBy(x => x.Value).Where(x => x.Count() > 1);

        Label1.Text += "<br /><br />dictionary duplicate values..........<br />";  
        foreach(var item in duplicatesValue)
        {
            Label1.Text += item.Key + "<br />";
        }
    }      
</script>      

<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - dictionary find duplicate values</title>      
</head>      
<body>      
    <form id="form1" runat="server">      
    <div>      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - dictionary find duplicate values
        </h2>      
        <hr width="550" align="left" color="Gainsboro" />      
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="Large"    
            >      
        </asp:Label>      
        <br /><br />    
        <asp:Button       
            ID="Button1"       
            runat="server"       
            Text="dictionary find duplicate values"      
            OnClick="Button1_Click"    
            Height="40"      
            Font-Bold="true"      
            />      
    </div>      
    </form>      
</body>      
</html>

c# - How to update a key in a Dictionary

Update a key in a dictionary
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method. We also can add some items to the Dictionary at the initializing time.

The following .net c# tutorial code demonstrates how we can update a key in a Dictionary. We know that the Dictionary element is consist of a key and value pair. The Dictionary keys are unique and we can’t set the same key for multiple items. But the Dictionary values can be duplicated and we can set the same value for the multiple items in a Dictionary.

There is no direct way to update a key for a specific item in the Dictionary object. We have to apply some tricks to achieve this. At first, we create an empty Dictionary instance. Then we put all elements of the source Dictionary into the newly created Dictionary instance. While we put the source Dictionary items into the new Dictionary, we have to alter/update the item whose key we have to update.

We put the updated element into the temporary Dictionary with the new key instead of the source element key. So, we get a duplicate Dictionary object but our desired element key is updated. Finally, we assign the temporary Dictionary elements to the source Dictionary. This way the source Dictionary’s specified key is updated.
dictionary-update-key.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Australian Pelican"},
            {2,"Brown Pelican"},
            {3,"Pygmy Cormorant"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //create a temporary dictionary
        Dictionary<int, string> temp = new Dictionary<int, string>();

        foreach (KeyValuePair<int,string> pair in birds)
        {
            //set ney key is old key plus 10
            int key = pair.Key + 10;
            temp.Add(key,pair.Value);
        }

        //assign temporary dictionary elements to old dictionary.
        birds = temp;

        Label1.Text += "<br /><br />dictionary elements after updating keys..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary update key</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary update key
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary update key"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to update a value in a Dictionary

Update a value in a dictionary
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. We can initialize an empty Dictionary instance and add elements to it using its Add() method. We also can add some items to the Dictionary at the initializing time.

The following .net c# tutorial code demonstrates how we can update a value in a Dictionary. Actually, this tutorial is for, how we can update a value in a specified element. Here we will update a value for a specified key.

We know that the Dictionary element is consist of a key and value pair. The Dictionary keys are unique and we can’t set the same key for multiple items. But the Dictionary values can be duplicated and we can set the same value for the multiple items in a Dictionary.

Updating a key in a Dictionary is difficult but we can update a value very easily. We can get an element from Dictionary by passing its key. When we get the element we can simply assign a new value to the specified element.
dictionary-update-value.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Eurasian Bittern"},
            {2,"Little Bittern"},
            {3,"Green Heron"},
            {4,"Squacco Heron"},
            {5,"Cattle Egret"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //update dictionary element value which key is 2
        birds[2] = "Goliath Heron";

        //update dictionary element value which key is 5
        birds[5] = "Great White Pelican";

        Label1.Text += "<br /><br />dictionary elements after updating..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary update value</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary update value
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary update value"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to add an item to a Dictionary if it does not exists

Dictionary add item if not exists
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can add an item to the Dictionary items collection if the item already not exists. A Dictionary item consists of a key and a value pair. In the entire Dictionary, the key must be unique but the value can be duplicated.

So, the logic is clear, if we want to add an item to the Dictionary items collection, at first we have to check whether the item key already exists in Dictionary or not. If the item key does not exist in the Dictionary then we can add the specified item to the Dictionary items collection.

We can add an item to the Dictionary by using Add() method. The Dictionary Add() method throws ArgumentException if an element with the same key already exists in the Dictionary object. So, when we check the item key existence in Dictionary and then add the item to the Dictionary, it helps us to avoid ArgumentException.

The Dictionary ContainsKey() method determines whether the Dictionary contains the specified key. Finally, after checking the key existence then we can add the specified element to Dictionary using its Add() method.
dictionary-add-if-not-exists.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Greater Flamingo"},
            {2,"Andean Flamingo"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //create new keyvaluepair
        KeyValuePair<int, string> pair1 = new KeyValuePair<int, string>(1, "Wood Stork");
        KeyValuePair<int, string> pair2 = new KeyValuePair<int, string>(3, "African Openbill");

        //add keyvaluepair to dictionary if key is not exists in dictionary.
        if (birds.ContainsKey(pair1.Key) == false)
        {
            birds.Add(pair1.Key, pair1.Value);
        }

        //add another keyvaluepair to dictionary if key is not exists in dictionary.
        if (birds.ContainsKey(pair2.Key) == false)
        {
            birds.Add(pair2.Key, pair2.Value);
        }

        Label1.Text += "<br /><br />dictionary elements after added new..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary add if not exists</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary add if not exists
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary add if not exists"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to get first key value from Dictionary

Dictionary get first key value
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can get the first key and value from a Dictionary. The .net frameworks have the built-in method to get the first key-value pair from a Dictionary instance. So the .net c# developers can easily get the first key-value pair from a Dictionary items collection.

The Enumerable First() method returns the first element of a sequence. The First() method throws InvalidOperationException if the source sequence is empty. And the Enumerable FirstOrDefault() method returns the first element of a sequence, or a default value if no element is found.

So, we can get the Dictionary’s first key-value pair using Enumerable First() and FirstOrDefault() methods. From the key-value pair, we can extract the key and value from it. In this tutorial, we get the Dictionary’s first key-value pair using the Enumerable FirstOrDefault() method.
dictionary-get-first-key-value.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {10,"Black Guillemot"},
            {20,"Rhinoceros Auklet"},
            {30,"Crowned Sandgrouse"},
            {40,"Speckled Pigeon"},
            {50,"Eurasian Collared Dove"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //get first keyvaluepair from dictionary.
        KeyValuePair<int, string> firstPairOfDictionary = birds.FirstOrDefault();

        Label1.Text += "<br /><br />dictionary first key value.........<br />";
        Label1.Text += firstPairOfDictionary.Key + " ........ " + firstPairOfDictionary.Value;
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary get first key value</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary get first key value
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary get first key value"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to get a key value pair from Dictionary

Get a key value pair from Dictionary
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can get a key-value pair from a Dictionary at a specified index position. Dictionary each item is consist of a key-value pair. So to get an item from a Dictionary also means to get a key-value pair from a Dictionary items collection.

We know that in the .net framework, we can get an element from a collection very easily. The .net c# developers can get a specified element from a collection using its index position.

The Enumerable ElementAt() method returns the element at a specified index in a sequence. And the Enumerable ElementAtOrDefault() method returns the element at a specified index in a sequence or a default value if the index is out of range. So this ElementAtOrDefault() method is safer than ElementAt() method.

In the following example .net c# code, we used both ElementAt() and ElementAtOrDefault() methods to get a specified element from a Dictionary items collection. We get the item from a Dictionary at a specified index position.
get-key-value-pair-from-dictionary.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {10,"Parasitic Skua"},
            {20,"Great Skua"},
            {30,"Atlantic Puffin"},
            {40,"Little Auk"},
            {50,"Guillemot"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //get keyvaluepair from dictionary at index 1.
        KeyValuePair<int, string> pairOfIndex1 = birds.ElementAt(1);

        //get keyvaluepair from dictionary at index 3.
        KeyValuePair<int, string> pairOfIndex3 = birds.ElementAtOrDefault(3);

        Label1.Text += "<br /><br />dictionary KeyValuePair at index 1......<br />";
        Label1.Text += pairOfIndex1.Key + " ........ " + pairOfIndex1.Value;

        Label1.Text += "<br /><br />dictionary KeyValuePair at index 3......<br />";
        Label1.Text += pairOfIndex3.Key + " ........ " + pairOfIndex3.Value;
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary find key by value</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - get key value pair from dictionary
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="get key value pair from dictionary"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to find a key by value in a Dictionary

Find a key by value in a dictionary
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. We can initialize an empty Dictionary instance and add elements to it using its Add() method. We also can add some items to the Dictionary at the initializing time.

The following .net c# tutorial code demonstrates how we can find a key by its value in a dictionary object. We know that the Dictionary element is consist of a key and value pair. The Dictionary keys are unique and we can’t set the same key for multiple items. But the Dictionary values can be duplicated and we can set the same value for the multiple items in a Dictionary.

So, in a Dictionary object, there might be multiple items with the same value. In this situation, we will take only the first element whose value matches our criteria after finding the items.

The Enumerable First() method returns the first element of a sequence. And the FirstOrDefault() method returns the first element of a sequence, or a default value if no element is found. So, we can find the first key by value in a Dictionary. We can easily pass the condition to the First() and FirstOrDefault() methods. The condition is matching the value. Then we can get the key from the returned element.
dictionary-find-key-by-value.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {10,"Sooty Tern"},
            {20,"Herring Gull"},
            {30,"Kelp Gull"},
            {40,"Black Skimmer"},
            {50,"South Polar Skua"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //get key of value 'Sooty Tern' from dictionary.
        int keyOfSootyTern = birds.FirstOrDefault(x => x.Value == "Sooty Tern").Key;

        //find key of value 'Kelp Gull' from dictionary.
        int keyOfKelpGull = birds.FirstOrDefault(x => x.Value == "Kelp Gull").Key;

        Label1.Text += "<br /><br />key of value Sooty Tern: " + keyOfSootyTern;
        Label1.Text += "<br />key of value Kelp Gull: " + keyOfKelpGull;
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary find key by value</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary find key by value
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary find key by value"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to get key by index from a Dictionary

Dictionary get key by index
.Net framework dictionary represents a collection of keys and values. each element of dictionary contain a key andvalue pair. so to get the dictionary key by index, first we need to find the specified element by index and then get thiselement's key.

Enumerable.ElementAt<TSource> method allow us to get the element at a specified index in a sequence. this method exists in System.Linqnamespace. this method type parameter is 'TSource' which represents type of the elements of 'source'. ElementAt() method require to pass twoparameters named 'source' and 'index'.

'source' parameter type is System.Collections.Generic.IEnumerable<TSource> which representsan IEnumerable<T> to return an element from. 'index' parameter value data type is System.Int32 which represents the zero based index of theelement to retrieve.

this method throw ArgumentNullException exception, if the 'source' is null. method also throw ArgumentOutOfRangeException exception, if the 'index' is less than zero or greater than or equal to the number of elements in 'source'.

Enumerable.ElementAt<TSource> method return value type is 'TSource' which represents the element at the specified index position of thesource sequence. so by using this method we can get an element of dictionary from a specified index. after retrieving the element we can get its'Key' by accessing Pair.Key. finally the process is Dictionary<TKey, TValue>.ElementAt(index).Key.

the following asp.net c# example code demonstrate us how can we get dictionary key by index programmatically at run timein an asp.net application.
dictionary-get-key-by-index.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {10,"Southern Lapwing"},
            {20,"Eurasian Golden Plover"},
            {30,"Grey Plover"},
            {40,"Ringed Plover"},
            {50,"Kentish Plover"}
        };

        Label1.Text = "dictionary elements with index..........";
        for (int i = 0; i < birds.Count; i++)
        {
            Label1.Text += "<br />" + "index: " + i;
            Label1.Text += " key: " + birds.ElementAt(i).Key;
            Label1.Text += " value: " + birds.ElementAt(i).Value;
        }

        //get key of dictionary element by index.
        int keyOfIndex1 = birds.ElementAt(1).Key;

        //get key of dictionary index 3 element.
        int keyOfIndex3 = birds.ElementAt(3).Key;

        Label1.Text += "<br /><br />key of dictionary element at index 1: " + keyOfIndex1;
        Label1.Text += "<br />key of dictionary element at index 3: " + keyOfIndex3;
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary get key by index</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary get key by index
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary get key by index"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to get index of an item by key from a Dictionary

Dictionary get item index by key
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can get an item index by its key from a Dictionary object. Each Dictionary item is built with a key-value pair. Dictionary keys are unique but values can be duplicated. So we can easily identify an item from a Dictionary using the specified item key.

This way, we can get the Dictionary item’s index position using its item key. To achieve this, at first, we converted the Dictionary keys to a list, then we get the specified key’s index position from this keys list.

The Enumerable ToList() method creates a List<T> from an IEnumerable<T>. The IndexOf() method determines the index of a specific item in the list.

Another way to get an item index from Dictionary items is that, loop through the items collection of the specified Dictionary. At the looping time, we match the specified key with each item, and when we get the item we also get the index of the item. The Enumerable ElementAt() method returns the element at a specified index in a sequence.
dictionary-index-of-key.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Banded Stilt"},
            {2,"Pied Avocet"},
            {3,"Blacksmith Plover"},
            {4,"Northern Lapwing"},
            {5,"Masked Lapwing"}
        };

        Label1.Text = "dictionary elements with index..........";
        for (int i = 0; i < birds.Count; i++)
        {
            Label1.Text += "<br />" + "index: " + i;
            Label1.Text += " key: " + birds.ElementAt(i).Key;
            Label1.Text += " value: " + birds.ElementAt(i).Value;
        }

        //find index of dictionary elements by key.
        int index = birds.Keys.ToList().IndexOf(3);

        Label1.Text += "<br /><br />index of key [3] is: " + index;

        //another way to find index of dictionary elements by key.
        for (int i = 0; i < birds.Count;i++ )
        {
            if (birds.ElementAt(i).Key == 4)
            {
                Label1.Text += "<br />index of key [4] is: " + i;
            }
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary index of key</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary index of key
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary index of key"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to convert Dictionary values to list

Convert dictionary values to list
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can convert Dictionary values to a list. Dictionary keys are unique but the values can be duplicated.

The Enumerable ToList() method creates a List<T> from an IEnumerable<T>. The ToList() method returns a List<T> that contains elements from the input sequence. The Enumerable ToList() method throws ArgumentNullException if the source is null.

The Enumerable ToList() method is located in System.Linq namespace. The ToList() method forces immediate query evaluation and returns a List<T> that contains the query results.
dictionary-to-list-of-values.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Spotted Antbird"},
            {2,"Ocellated Antbird"},
            {3,"Squamate Antbird"},
            {4,"Barred Antshrike"},
            {5,"Great Antshrike"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //this line create a generic list by dictionary values.
        List<string> valuesList = birds.Values.ToList();

        Label1.Text += "<br /><br />list elements..........";
        foreach (string bird in valuesList)
        {
            Label1.Text += "<br />" + bird;
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary to list of values</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary to list of values
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary to list of values"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to remove first element from Dictionary

Remove first element from dictionary
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can remove the first element from a Dictionary. The Dictionary elements are the collection of key-value pairs. So this tutorial will demonstrate how we can remove the first key-value pair from a Dictionary object.

The Dictionary Remove() method removes the value with the specified key from the Dictionary<TKey,TValue>. The Remove() method has a parameter named ‘TKey key’, this is the key of the element to remove. So, if we pass the Dictionary first element key to the Remove() method then it will remove the first element from the Dictionary instance.

In this c# tutorial code, we converted the Dictionary keys to a list and get the first key from the list. This key is the first element key of the Dictionary. Now we pass this key to the Dictionary Remove() method that removes the first element from Dictionary.The Remove() method returns a Boolean. It returns true if the element is successfully found and removed; otherwise, it returns false if the key is not found in the Dictionary. The Dictionary Remove() method throws ArgumentNullException if the provided key is null.
dictionary-remove-first-element.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Tundra Swan"},
            {2,"Hawaiian Goose"},
            {3,"Egyptian Goose"},
            {4,"Orinoco Goose"},
            {5,"Andean Goose"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int , string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //this line remove/delete dictionary first keyvaluepair.
        birds.Remove(birds.Keys.First());

        //alternate way to remove dictionary first element.
        //birds.Remove(birds.Keys.FirstOrDefault());

        Label1.Text += "<br /><br />dictionary keys and values after remove first pair.....";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary remove first element</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary remove first element
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary remove first element"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to make Dictionary TryGetValue case insensitive

Dictionary TryGetValue() case insensitive
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can use Dictionary TryGetValue() method. In this .net c# tutorial code we will also demonstrate how we can use Dictionary TryGetValue() method in a case-insensitive way. So, we will pass a key in a different case instead the original case such as ‘SNOW Goose’ instead of ‘Snow Goose’.

The Dictionary TryGetValue() method gets the valueAssociated with the specified key. The TryGetValue() method has two parameters named ‘TKey key’ and ‘out TValue value.’ The first parameter is the key of the value to get. And the second parameter is value.

When this method returns, contains the value associated with the specified key if the key is found; otherwise the default value for the type of the value parameter.

The Dictionary TryGetValue() method returns true if the Dictionary contains an element with the specified key otherwise it returns false. The TryGetValue() method throws ArgumentNullException if the key is null.
dictionary-trygetvalue-case-insensitive.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<string, int> birds = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) {
            {"Swan Goose",10},
            {"Snow Goose",20},
            {"Canada Goose",30},
            {"Whooper Swan",40}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<string, int> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        int value;
        string key = "SNOW Goose";

        Label1.Text += "<br /><br />key [" + key + "] value is: "; 

        if (birds.TryGetValue(key, out value))
        {
            Label1.Text += value;
        }
        else
        {
            Label1.Text += "key [" + key + "] does not exists in dictionary";
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary trygetvalue case insensitive</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary trygetvalue case insensitive
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary trygetvalue case insensitive"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to sort a Dictionary by DateTime value

Sort a Dictionary by DateTime value
The Dictionary class represents a collection of keys and values. The .net framework’s Dictionary is located under the System.Collections.Generic namespace. We can initialize an empty Dictionary instance and add elements to it using its Add() method. We also can add some items to the Dictionary at the initializing time.

The following .net c# tutorial code demonstrates how we can sort Dictionary elements by DateTime value. How can we sort Dictionary items in ascending and descending order while their values are DateTime data type?

In this .net c# tutorial code we initialize a Dictionary instance whose value data type is DateTime and the key data type is Int. We have to sort the Dictionary elements in ascending and descending order by their DateTime data type values. By default, Dictionary object holds their elements as they are added or put in initializing time.

The Enumerable OrderBy() method sorts the elements of a sequence in ascending order and the OrderByDescending() method sorts the elements of a sequence in descending order. So we can sort the Dictionary elements in ascending and descending order using this OrderBy() and OrderByDescending() methods. The Enumerable OrderBy() and OrderByDescending() methods are located under the System.Linq namespace.

The Enumerable OrderBy() method returns an IOrderedEnumerable<TElement> whose elements are sorted according to a key and the OrderByDescending() method returns an IOrderedEnumerable<TElement> whose elements are sorted in descending order according to a key. The Enumerable ToDictionary() method creates a Dictionary<TKey,Tvalue> from an IEnumerable<T>.
dictionary-sort-by-datetime.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with date time values.
        Dictionary<int, DateTime> dc = new Dictionary<int, DateTime>() {
            {1,DateTime.Today},
            {2,DateTime.Today.AddDays(3)},
            {3,DateTime.Today.AddDays(1)},
            {4,DateTime.Today.AddDays(10)},
            {5,DateTime.Today.AddDays(5)},
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, DateTime> pair in dc)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value.ToShortDateString();
        }

        //ascending sorted dictionary by date time value.
        dc = dc.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        Label1.Text += "<br /><br />ascending sorted dictionary by date time value..........";
        foreach (KeyValuePair<int, DateTime> pair in dc)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value.ToShortDateString();
        }

        //descending sorted dictionary by date time values.
        dc = dc.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        Label1.Text += "<br /><br />descending sorted dictionary by date time values..........";
        foreach (KeyValuePair<int, DateTime> pair in dc)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value.ToShortDateString();
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary sort by datetime</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary sort by datetime
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary sort by datetime"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to sort a Dictionary in ascending and descending order

Dictionary sort order
The Dictionary class represents a collection of keys and values. .Net framework’s Dictionary is located under the System.Collections.Generic namespace. The Dictionary object constructor is Dictionary<TKey,TValue>. The TKey is the data type of the keys in the Dictionary and the TValue is the data type of the values in the Dictionary. We can initialize an empty Dictionary instance and add elements to it using its Add() method.

The following .net c# tutorial code demonstrates how we can sort Dictionary elements. And how .net developers can sort dictionary elements in both ascending and descending order? How .net c# developers can sort dictionary items by their keys or values.

The .net c# developers can sort Dictionary items by their keys in both ascending and descending order and they also can sort Dictionary items by their values both in ascending and descending order. In the following example code, we sort Dictionary elements in descending order by their keys, and we also sort Dictionary elements in ascending order by their values.

The Enumerable OrderBy() method sorts the elements of a sequence in ascending order. We sort the Dictionary elements by their values in ascending order using this OrderBy() method.

The Enumerable OrderByDescending() method sorts the elements of a sequence in descending order. In this example we sort Dictionary items by their keys in descending order using this OrderBYDescending() method.

The Enumerable OrderBy() method and OrderByDescending methods exist in System.Linq namespace.

The Enumerable ToDictionary() method creates a Dictionary<TKey,TValue> object from an IEnumerable<T>.
dictionary-sort-order.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Cuban Amazon"},
            {2,"Pheasant Cuckoo"},
            {3,"African Emerald Cuckoo"},
            {4,"Regent Parrot"},
            {5,"Guira Cuckoo"}
        };

        Label1.Text = "birds dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //descending sorted dictionary by keys.
        birds = birds.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

        Label1.Text += "<br /><br />descending sorted dictionary by keys..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //ascending sorted dictionary by values.
        birds = birds.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

        Label1.Text += "<br /><br />ascending sorted dictionary by values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary sort order</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary sort order
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary sort order"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>