Thursday 2 May 2013

Get only specific type of value from array which contains many types of values from object array using LINQ With C#.Net and VB.Net Examples

Using LINQ we can get specific type of object from Object Type array which contains many types of object. We are using "OfType" generic method to return only the elements of the array that  we specified.

Here is example for this.
In this example we take one array whose type is object and which contains many types of object, i.e. string, integer, double, Dictionary etc...
Now we get only doubles value using LINQ and display, after that, we get Dictionary object using LINQ and display. You can see the output for that.



C#. Net Example :
        Dictionary<int, string> oDictionary = new Dictionary<int, string>();
        oDictionary.Add(1, "a");
        object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0, oDictionary };

        var doubles = numbers.OfType<double>();

        Response.Write("<b>Numbers stored as doubles:</b>");
        Response.Write("</br>");
        foreach (var d in doubles)
        {
            Response.Write(d.ToString());
            Response.Write("</br>");
        }

        var lstDictionary = numbers.OfType<Dictionary<int, string>>();
        Response.Write("</br>");
        Response.Write("<b>Dictionary objects :</b>");
        Response.Write("</br>");
        foreach (Dictionary<int, string> d in lstDictionary)
        {
            
            Response.Write( d.ToString());
            Response.Write("</br>");
        }   

VB.Net Examples :
        Dim oDictionary As New Dictionary(Of Integer, String)()
        oDictionary.Add(1, "a")
        Dim numbers As Object() = {Nothing, 1.0, "two", 3, "four", 5, "six", 7.0, oDictionary}

        Dim doubles = numbers.OfType(Of Double)()

        Response.Write("<b>Numbers stored as doubles:</b>")
        Response.Write("</br>")
        For Each d As Double In doubles
            Response.Write(d.ToString())
            Response.Write("</br>")
        Next

        Dim lstDictionary = numbers.OfType(Of Dictionary(Of Integer, String))()
        Response.Write("</br>")
        Response.Write("<b>Dictionary objects :</b>")
        Response.Write("</br>")
        For Each d As Dictionary(Of Integer, String) In lstDictionary

            Response.Write(d.ToString())
            Response.Write("</br>")
        Next

Output :
LINQ Conversion

No comments:

Post a Comment