Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SequenceEqual and then returning which elements don't match

I have two List<string> and I am using the SequenceEqual method to determine if they match.

I now have a need to get a List<int>, string, IEnumerable, whatever of the indexes of the elements that have failed.

Is there an easy way?

Thanks

like image 452
Jon Avatar asked Dec 01 '11 13:12

Jon


3 Answers

I think you want:

List<string> list1 = ...
List<string> list2 = ...

var differentIndices = list1.Zip(list2, (item1, item2) => item1 == item2)
                            .Select((match, index) => new { Match = match, Index = index })
                            .Where(a => !a.Match)
                            .Select(a => a.Index);

Note that if one of the lists is longer than the other, this will not consider the items beyond the length of the smaller list.

like image 132
Ani Avatar answered Sep 24 '22 13:09

Ani


You can use LINQ:

var firstFiltered = firstList.Except(secondList);
var secondFiltered = secondList.Except(firstList);

var bothFiltered = firstFiltered.Concat(secondFiltered);

Note: I'm sure there is a more efficient way of doing this...

like image 39
myermian Avatar answered Sep 24 '22 13:09

myermian


It sounds like you want the opposite of the "intersection". The intersection is the items that exist in both lists ... and you want the items that don't exist in both lists.
Here's a easy one-liner to do that:

var items = first.Union(second).Except(first.Intersect(second));

Example:

var first = new[]{"A","B","C","D"};
var second = new[]{"C","D","E","F"};

var items = first.Union(second).Except(first.Intersect(second));
// Result: "A","B", "E","F"
like image 30
Scott Rippey Avatar answered Sep 22 '22 13:09

Scott Rippey