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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With