Wednesday, 8 May 2013

.Net Tips: Convert two dimensional array in to Dictionary object using LINQ With C#.Net and VB.Net Examples

Using LINQ we can convert array in to dictionary object. We can use "ToDictionary" LINQ method to get dictionary object from array.
But we need to make sure that the key value should be unique in array, otherwise it will generate error "An item with the same key has already been added.".

Here is example for that.
In this example we take one two dimensional array "CustomerDetails". This array contains ID and Name of customer. Now using "ToDictionary" method of this array we can get dictionary object of type "Dictionary<int, string>". You can get your desirable type of Dictionary object.


C#. Net Example :
        var CustomerDetails = new[] { new {ID = 1 ,Name = "Alice"},
                                new {ID = 2 ,Name = "Bob"  },
                                new {ID = 3 ,Name = "Cathy"},
                                };

        Dictionary<int, string> oDictionary = new Dictionary<int, string>();
        oDictionary = CustomerDetails.ToDictionary(sr => sr.ID, sr => sr.Name);

        foreach (KeyValuePair<int, string> d in oDictionary)
        {
            Response.Write("<b>Key : </b>" + d.Key + " , <b>Value : </b>" + d.Value);
            Response.Write("</br>");
        }

VB.Net Examples :
        Dim CustomerDetails = {
                                New With { _
                                    Key .ID = 1, _
                                    Key .Name = "Alice" _
                                }, _
                                New With { _
                                    Key .ID = 2, _
                                    Key .Name = "Bob" _
                                }, _
                                New With { _
                                    Key .ID = 3, _
                                    Key .Name = "Cathy" _
                                }
                              }

        Dim oDictionary As New Dictionary(Of Integer, String)()
        oDictionary = CustomerDetails.ToDictionary(Function(sr) sr.ID, Function(sr) sr.Name)

        For Each d As KeyValuePair(Of Integer, String) In oDictionary
            Response.Write(("<b>Key : </b>" & d.Key & " , <b>Value : </b>") & d.Value)
            Response.Write("</br>")
        Next

Output :

3 comments:

  1. vb.net collection samples

    http://vb.net-informations.com/collections/vb.net_collections_tutorials.htm

    ReplyDelete
  2. This is not a 2 dimentional array, it is an array of objects. A 2 dimensional array would be string[5][5] stuff.

    ReplyDelete
    Replies
    1. This is another type of two dimensional array. We can also create two dimensional array like this. You can see that there is no object of any physical class.

      Delete