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>
More c# examples