简体   繁体   中英

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM