Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the 1st match between 2 string arrays

I have 2 string arrays. The one is the base and the other is changing.

string[] baseArray = { "Gold", "Silver", "Bronze" };
string[] readArray = { "Bronze", "Silver", "Gold" };

// After comparing the readArray over the baseArray the result should be this
//string match = "Gold";

I want to get the 1st in order of the baseArray.

//Example2
string[] readArray = { "Bronze", "Silver" };
//string match should be "Silver"
like image 653
Incognito Avatar asked Sep 16 '25 01:09

Incognito


1 Answers

If you only want one result, using LINQ:

string firstMatch = baseArray.FirstOrDefault(readArray.Contains);

If you only want one result, not using LINQ:

string firstMatch = null;
foreach(string element in baseArray)
{
    if (Array.IndexOf(readArray, element) >= 0)
    {
        firstMatch = element;
        break;
    }
}

If you want all matching elements, using LINQ:

string[] common = baseArray.Intersect(readArray).ToArray();

If you want all matching elements, not using LINQ:

HasSet<string> common = new HashSet<string>(readArray);
result.Intersect(baseArray);
like image 73
Martin Mulder Avatar answered Sep 17 '25 15:09

Martin Mulder