+92 332 4229 857 99ProjectIdeas@Gmail.com

How to join two string arrays and extract matching strings



How to join two string arrays and extract matching strings:

For example: You have the following two string arrays and you want extract the matching strings from both. Then through LINQ you can do this: In this particular example “this”, “is” and “LINQ” are same in both strings.

string[] str = new string[] { "hello", "world" , "this", "is", "LINQ" };
string[] str2 = new string[] { "this", "is" , "C#", "LINQ", "query" };

Code

In the query: joining each string from str on each string of str2 and in the end, if found match strings from both then put them in a list.

   List<string> query =
          (from string st in str
           join s in str2 on st equals s
           select s).ToList();

Displaying the list:

           foreach (var item in query)
           {
               Console.WriteLine(item.ToString());
           }

Output of the program is:

              this
               is
       LINQ

ANOTHER WAY THROUGH SIMPLE FOR LOOPS:

Create a new string where to hold the match values from both string arrays:

   string[] st = new string[10]; 
   int k = 0;

    for (int i = 0; i < str.Length; i++)
    {
        for (int j = 0; j < str2.Length; j++)
         {

              if (str[i].Equals(str2[j]))
              {
                  st[k] = str[i];
                  k++;
              }
        }
             
   }

Displaying the new string array:

           for (int i = 0; i < k; i++)
           {
               Console.WriteLine(st[i]);
           }


Output of the program is:

              this
               is
       LINQ

0 comments: