Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a LINQ equivalent method?

Tags:

c#

.net

linq

I know LINQ has a SequenceEquals method. This method makes sure each item value in each collection matches, in the same order.

What I'm looking for is a more "Equivalent" type of functionality. Just that both sequences contain the same items, not necessarily in the same order.

For example, nUnit has CollectionAssert.AreEqual() and CollectionAssert.AreEquivalent() that do what I'm explaining.

I know that I can do this either by:

  1. Ordering the lists ahead of time and using SequenceEquals
  2. Using Intersect, then seeing if the intersection is equal to the original sequence.

Example:

var source = new[] {5, 6, 7};
source.Intersect(new[] {5, 7, 6}).Count() == source.Length;
like image 468
CubanX Avatar asked Sep 21 '10 13:09

CubanX


People also ask

Is there a LINQ equivalent in Java?

NET, an easy way for you to simplify querying datasets is LINQ. Java doesn't have this, but since the introduction of Java 8 in 2014, you do now have the possibility to use "streams". Both LINQ and streams are ways to simplify querying datasets and to provide developers with an easy API to use.

Which method is valid in LINQ?

The LINQ join methods are supported in LINQ to Entities, with the exception of those that accept an IEqualityComparer because the comparer cannot be translated to the data source.

What are LINQ extension methods?

Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ.


2 Answers

You could build a set and then use HashSet<T>.SetEquals. It's not strictly within LINQ, but it plays nicely with it :)

Of course, you could easily write your own extension method to extend this. Something like this:

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 comments, this ignores the number of times elements occur, as well as the ordering - so { 1, 2 } would be "set equal" to { 1, 2, 1, 2, 1, 1, 1 }. If that's not what you want, it'll get a little more complicated.

like image 139
Jon Skeet Avatar answered Oct 02 '22 04:10

Jon Skeet


I would create an extension method that does the intersect and then compares the counts.

like image 44
Toby Avatar answered Oct 02 '22 03:10

Toby