user10502356
user10502356

Reputation: 3

Check if two strings are in two different arrays but on the same position

So I have two arrays with names, and I want to check if, given two names, they are each in one of the arrays and in the same position. For example, if I have the names "Mike" and "Charles" and the arrays ["John", "Mike", "Sophie"] and ["Ellie", "Charles", "Ryan"], it returns true.

I'm making a Secret Santa program and I don't want couples to have each other as Secret Santa.

Upvotes: 0

Views: 100

Answers (4)

Danny Goodall
Danny Goodall

Reputation: 838

Array.IndexOf sounds like what you're looking for.

string[] firstArray = new string[] { "John", "Mike", "Sophie" };
string[] secondArray = new string[] { "Ellie", "Charles", "Ryan" };

string firstName = "Mike";
string secondName = "Charles";

return Array.IndexOf(firstArray, firstName) == Array.IndexOf(secondArray, secondName);

Upvotes: 4

Furkan Öztürk
Furkan Öztürk

Reputation: 1416

You can try the following,

        var index1 = Array.IndexOf(new[] { "John", "Mike", "Sophie" }, "Mike");
        var index2 = Array.IndexOf(new[] { "Ellie", "Charles", "Ryan" } , "Charles");
        return index1 == index2 && index1 != -1;

Upvotes: 0

Jitu Batiya
Jitu Batiya

Reputation: 159

    string[] firstArray = new string[] { "John", "Mike", "Sophie" };
    string[] secondArray = new string[] { "Ellie", "Charles", "Ryan" };

    string firstName = "Sophie";
    string secondName = "Ryan";     
    return (Array.IndexOf(firstArray, firstName) == Array.IndexOf(secondArray, 
           secondName));

Upvotes: 0

Gnyasha
Gnyasha

Reputation: 684

You may try this.

var firstArray = new string[] { "John", "Mike", "Sophie" };
var secondArray = new string[] { "Ellie", "Charles", "Ryan" };

var firstName = "Mike";
var secondName = "Charles";

var firstNameIndex = firstArray.ToList().FindIndex(a => a == firstName);
var secondNameIndex = secondArray.ToList().FindIndex(a => a == secondName);

if (firstNameIndex == secondNameIndex && (firstNameIndex != -1 || secondNameIndex != -1))
{
return  true;
}
 else
{
return  false;
}

Upvotes: 0

Related Questions