Vincenzo
Vincenzo

Reputation: 1811

Compare element order of two string list

I have a first list of string :

"GENRE",
"NATIONALITY",
"PRODUCTION",
"FIRSTYEAR",
"LASTYEAR",
"FILTER"

I have a second list of string:

"NATIONALITY"
"LASTYEAR"
"FILTER"

I would like to check if element in the second list (even if some element are missing) are in the same order as the first list.

Example :

"NATIONALITY"
"LASTYEAR"
"FILTER"

must return TRUE and

"LASTYEAR"
"NATIONALITY"
"FILTER"

must return FALSE because "NATIONALITY" has to be before "LASTYEAR" accordingly to the first list

I have tried to get index with "IndexOf" of each element but I don't know how to compare them effectively.

Is a good to solution to use a Custom Comparer (implementing IComparer) in this case ? If yes how ? Is it better to use Enum to achieve this comparison ?

Need help thanks in advance

Upvotes: 0

Views: 2665

Answers (2)

Selman Genç
Selman Genç

Reputation: 101681

You can use Intersect to get intersection between your lists, then use SequenceEqual method to check if that sequence is the same as list2:

list1.Intersect(list2).SequenceEqual(list2);

Upvotes: 5

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112334

I start by filtering the first list to make it contain only the items contained in the second list.

var list1Filtered = list1
    .Where(x => list2.Contains(x))
    .ToList()

If you are sure that all the items contained in the second list are contained in the first list as well and that they are unique in both lists, you can drop the following check

if (list1Filtered.Count != list2.Count) {
    return false;
}

Now it is easy to make the comparison

for (int i = 0; i < list2.Count; i++) {
    if (list2[i] != list1Filtered[i]) {
        return false;
    }
}
return true;

Upvotes: 1

Related Questions