If I have 2 int arrays a and b and they contain data like this..
a[0] = 1
a[1] = 3
a[2] = 7
b[0] = 6
b[1] = 3
b[2] = 5
How can I check if all the pairs of numbers are unique e.g. that each combination of a[i] and b[i] at the same index is not repeated in the rest of the array… So the above data would pass but if I introduced this below it would fail..
a[24] = 7
b[24] = 5
Because this combination already exists in the array at index 2. Can I do this in LINQ?
>Solution :
If the order of the values in the pairs over the two arrays is significant (i.e. a[0] == 1, b[0] == 2 is considered different from a[0] == 2, b[0] == 1) then one way to check for uniqueness using Linq is as follows:
bool unique = a.Zip(b).Distinct().Count() == a.Length;
If the order of the values in the pairs is NOT significant, it’s slightly more fiddly:
bool unique = a.Zip(b).DistinctBy(
x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second)))
.Count() == a.Length;
These solutions assume that missing values in one of the arrays will be ignored.
(Note: DistinctBy() is only available in .Net 6.0 or later, or via a NuGet package.)