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
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.
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...
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With