Saturday, 9 June 2012

.Net Beginners , C# Tips : Get common values from two arrays using LINQ

Using LINQ you are able to fin common values amoung two arrays.
There is a one method "Intersect" in LINQ to get intersect values.
Here are sample example for this.
In this example we have two arrays of integer and find common values of that arrays.

C# Example :
        int[] arrayNumbersA = { 5, 0, 9, 10, 50, 6, 4, 3, 1 };
        int[] arrayNumbersB = { 10, 11, 51, 1, 0 };

        int[] arrayCommon = arrayNumbersA.Intersect(arrayNumbersB).ToArray(); ;

        Response.Write("<b>Common values :</b><br/>");
        foreach (var intValue in arrayCommon)
        {
            Response.Write(intValue);
            Response.Write("<br/>");
        }
        Response.Write("<br/>");
        Response.Write("<br/>");

VB.net Example :
        Dim arrayNumbersA() As Integer = {5, 0, 9, 10, 50, 6, 4, 3, 1}
        Dim arrayNumbersB() As Integer = {10, 11, 51, 1, 0}

        Dim arrayCommon() As Integer = arrayNumbersA.Intersect(arrayNumbersB).ToArray()

        Response.Write("<b>Common values :</b><br/>")
        For Each intValue As Integer In arrayCommon
            Response.Write(intValue)
            Response.Write("<br/>")
        Next
        Response.Write("<br/>")
        Response.Write("<br/>")
Output :
You can also use other data types like string , decimal , double etc...

No comments:

Post a Comment