El Mac
El Mac

Reputation: 3419

IEqualityComparer Exception with Linq (NotSupportedException)

I was doing a custom Comparer to compare two classes in a Linq query like this one:

Table<Info> table = context.GetTable<Info>();
bool infoAlreadyExists = table.Contains(info, new MyComparer());

This is my comparer:

public class MyComparer : IEqualityComparer<Info>
{

    #region IEqualityComparer<Info> Member

    public bool Equals(Info x, Info y)
    {
        return x.Content == y.Content;
    }

    public int GetHashCode(Info obj)
    {
        return obj.Content.GetHashCode();
    }

    #endregion
}

The problem is that I get an exception. [System.NotSupportedException]

The exception tells me that a not supported overload for the Contains operator was found. Do I do something wrong or is it really NotSupported? I couldn't find anything on the documentation.

This is the definition of the overload I am trying to use of the contains method.

public static bool Contains<TSource>(this IQueryable<TSource> source, TSource item, IEqualityComparer<TSource> comparer);

Upvotes: 1

Views: 540

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

That version of Contains method is not supported.You can see the full list here:

So you need to perform this operation in memory, you can use AsEnumerable for that.

But in this case it seems you don't need that equality comparer. You can just use the below query to get the same result:

table.FirstOrDefault(x => x.Content == info.Content) != null;

Upvotes: 2

Related Questions