Is there an equivalent LINQ method?

I know LINQ has a SequenceEquals method. This method ensures that each element value in each collection matches in the same order.

What I'm looking for is a more "equivalent" type of functionality. Itโ€™s just that both sequences contain the same elements, not necessarily in the same order.

For example, nUnit has CollectionAssert.AreEqual() and CollectionAssert.AreEquivalent() , which do what I explain.

I know that I can do this either:

  • Order lists well in advance and with SequenceEquals
  • Using Intersect , let's see if the intersection matches the original sequence.

Example:

 var source = new[] {5, 6, 7}; source.Intersect(new[] {5, 7, 6}).Count() == source.Length; 
+6
c # linq
source share
3 answers

I would create an extension method that does the intersection and then compares the numbers.

+8
source share

You can create a set and then use HashSet<T>.SetEquals . It's not strictly LINQ, but it plays great with it :)

Of course, you can easily write your own extension method to extend it. Something like that:

 public static bool SetEquals<T>(this IEnumerable<T> source, IEnumerable<T> other) { HashSet<T> hashSet = new HashSet<T>(source); return hashSet.SetEquals(other); // Doesn't recurse! Calls HashSet.SetEquals } 

EDIT: As noted in the comments, this ignores the number of times the elements occur, as well as the order - so { 1, 2 } will be "set equal" to { 1, 2, 1, 2, 1, 1, 1 } . If this is not what you want, it will be a little harder.

+9
source share

I did it as follows:

 public static bool SetEquivalent<T>( this IEnumerable<T> aSet, IEnumerable<T> anotherSet) { var diffA = aSet.Except(anotherSet).Count(); var diffB = anotherSet.Except(aSet).Count(); return diffA == diffB && diffA == 0; } 
+2
source share

All Articles