Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a distinct, case-insensitive list using Linq and Entity Framework

I need to get a case-insensitive list from the results of an entity framework query. I have the following:

 var myList = myEF.GroupBy(e => new { e.Code, e.Description })
            .Select(e => e.First())
            .ToList();

That gives me a distinct list, but it's case-sensitive. I need case-insensitive.

I figured I should be able to do something like this:

var myList = myEF.GroupBy(e => new { e.Code, e.Description }, StringComparer.InvariantCultureIgnoreCase)
            .Select(e => e.First())
            .ToList();

But that doesn't seem to want to work with the anonymous object.

Adding .ToLower or .ToLowerInvariant doesn't seem to work either. Nor does using Distinct(StringComparer.InvariantCultureIgnoreCase) instead of the GroupBy.

Seems there ought to be an easy way to do this, but I'm not finding it.

like image 564
BDW Avatar asked Oct 21 '22 01:10

BDW


1 Answers

I tried various methods you said and all of them did fail. I got this working however:

var distinct = list.Distinct(new CaseInsensitiveComparer());

public class CaseInsensitiveComparer : IEqualityComparer<A>
{
    public bool Equals(A x, A y)
    {
        return x.Code.Equals(y.Code, StringComparison.OrdinalIgnoreCase) &&
               x.Description.Equals(y.Description, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(A obj)
    {
        return obj.Code.ToLowerInvariant().GetHashCode();
    }
}

Feel free to tweak to your needs.

Fiddle

like image 96
Mrchief Avatar answered Oct 22 '22 16:10

Mrchief