-2

I want to compare two string arrays and just return values which are contained in both arrays.

Example:

 string[] a = ["A", "B", "C", "D"];
 string[] b = ["A", "E", "I", "M", "Q", "U", "Y"];

Expected outcome would be

 string[] result = ["A"];
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

4 Answers4

6

Contains() should help here

string[] a1 = { "A","B", "C", "D" };
string[] a2 = { "A", "E", "I", "M", "Q", "U" ,"Y" };

string[] result = a1.Where(a2.Contains).ToArray();
fubo
  • 44,811
  • 17
  • 103
  • 137
5

You could use LINQ's Intersect:

var arrayA = new string[] { "A", "B", "C", "D" };
var arrayB = new string[] { "A", "E", "M", "Q", "U", "Y" };
var matchingItems = arrayA.Intersect(arrayB);
var firstMatchingItem = arrayA.Intersect(arrayB).First();

Note that Intersect produces a distinct (unique) set as a result.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
0

You could use LINQ as advised or use 2 for loops like that:

        string[] a1 = { "A", "B", "C", "D" };
        string[] a2 = { "A", "E", "I", "M", "Q", "U", "Y" };

        for(int i = 0; i < a1.Length; i++)
            for(int y = 0; y < a2.Length; y++)
                if(a1[i]==a2[y])
                {
                    //Code
                }
Ido H Levi
  • 181
  • 9
0

In general case when same items can appear several times you can try GroupBy:

  // Expected anewer: [A, B, A] 
  // since A appears two times in b only, B - just once
  string[] a = new[] { "A", "B", "A", "C", "A", "D" };
  string[] b = new[] { "A", "E", "I", "M", "A", "Q", "U", "B" };

  var quantities = b
    .GroupBy(item => item)
    .ToDictionary(chunk => chunk.Key, chunk => chunk.Count());

  string[] result = a
    .Where(item => quantities.TryGetValue(item, out var count) && 
                   ((quantities[item] = --count) >= 0))
    .ToArray();

  Console.Write(string.Join(", ", result));

Outcome:

  A, B, A
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215