Zhrez Pain
Zhrez Pain

Reputation: 339

Compare 2 string array elements and return

I am actually an SQL developer but now working on C# and LINQ. I have a logic in my mind but due to technical barrier I am not able to implement it.

I will have 2 string array. And below are the conditions I want to implement,

  1. I want to find if array 2 elements are present in array 1.
  2. Then check sequence of elements of both the arrays.

For ex. Correct case

string 1: {"ID","Name","Age","Address","Gender","Phone"}

string 2: {"ID","Name","Phone"}

So this should return true, as all array 2 elements are present in array 1 and sequence is also correct.

Wrong Case

string 1: {"ID","Name","Age","Address","Gender","Phone"}

string 2: {"ID","Name","Phone","Address"}

This should return false, although array 2 elements are present in array 1, "Phone" is appears before "Address", but in array 1 "Address" comes before "Phone". Sequence is incorrect so it should return false.

Is this possible? I haven't wrote any code as I am completely new to LINQ. Just quide me if this is possible in C# if not LINQ,

Upvotes: 3

Views: 134

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38880

You can use Intersect and SequenceEqual:

string[] a = new [] {"ID","Name","Age","Address","Gender","Phone"};
string[] b = new [] {"ID","Name","Phone"};
string[] c = new [] {"ID","Name","Phone","Address"};

Console.WriteLine(a.Intersect(b).SequenceEqual(b));
Console.WriteLine(a.Intersect(c).SequenceEqual(c));

Intersect will get elements that are present in both a and b, and then SequenceEqual will ensure that they are in the same order.

It's worth noting that Intersect() effectively calls .Distinct(), so it will only work if the lists contain unique elements only. Duplicate items in either list will be ignored by the Intersect().

Fiddle

Upvotes: 6

Sweeper
Sweeper

Reputation: 275115

This is one solution:

var mapped = b.Select(x => Array.IndexOf(a, x));
if (!mapped.Contains(-1) && mapped.OrderBy(x => x).SequenceEqual(mapped)) {
    Console.WriteLine("Correct Case");
} else {
    Console.WriteLine("Wrong Case");
}

where a and b are array 1 and array 2 respectively. There might be more efficient solutions available.

The logic is quite simple, we select the index of each element of b in a. If one element in b is not in one, there will be a -1 in the result. I also checked whether mapped.OrderBy(x => x).SequenceEqual(mapped). If b has a's elements in the same order, then the indices should be in ascending order.

Upvotes: 2

Related Questions