Search code examples
c#entity-frameworklinqlinq-to-entities

Custom compare for GroupBy method in a query


I want to put objects with specific values(in this case (int?)null) in different groups.

So this:

Id  NullableInt
A      1
B      2
C      1
D     null
E     null
F      1
G     null

Should end up as this:

Key   Ids
1      A, C, F
2      B
null   D
null   E
null   G

I am using .GroupBy with a custom comparer to try and achieve this.

The problem is that getting an error

LINQ to Entities does not recognize the method, and this method cannot be translated into a store expression

When I test the LINQ expression on its own it works so I assume that its not supported or works differently in Entity Framework, but I can't find any information on it.

My code (simplified):

var result = db.Table
    ...
    .GroupBy(
        t => t.NullableInt,
        new NullNotEqualComprare())
    ...
    .ToList();

Obviously I want to do as much as possible in the database itself.

The Comparer code:

    private class NullNotEqualComparer : IEqualityComparer<int?>
    {
        public bool Equals(int? x, int? y)
        {
            if (x == null || y == null)
            {
                return false;
            }

            return x.Value == y.Value;
        }

        public int GetHashCode(int? obj)
        {
            return obj.GetHashCode();
        }
    }

Am I doing something wrong and if it is not supported, how can I solve this problem?


Solution

  • In the end I went with a bit of a hack, but its quite simple and works well. I thought I would write it down here since it might be useful for others.

    In my question the NullableInt is actually an id to a different table and so I know that it will always be above zero.

    For this reason I can do something like this:

    var result = db.Table
        ...
        .GroupBy(t => t.NullableInt ?? int.MinValue + t.Id)
        ...
        .ToList();