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

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

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

This gives me a great list, but it is case sensitive. I need case insensitivity.

I decided that I could do something like this:

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

But this is not like working with an anonymous object.

Adding .ToLower or .ToLowerInvariant does not work either. Does not use Distinct(StringComparer.InvariantCultureIgnoreCase) instead of GroupBy .

There seems to be an easy way to do this, but I can't find it.

+5
source share
3 answers

I tried the various methods that you said and all of them failed. However, I got this work:

 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 customize your needs.

Fiddle

+3
source

For this request you will need 2 passes.

The first query to convert to lowercase, the second to group.

Only escape sequences can be what you can extract in uppercase right from the Entity Framework.

Or with additional EF / LINQ features that are still under development :(

0
source

Restless, but it works:

 private class StructuralTupleComparer<T>: IEqualityComparer<Tuple<T, T>>{ private IEqualityComparer<T> _cmp; public StructuralTupleComparer(IEqualityComparer<T> cmp){ this._cmp = cmp } public bool Equals(Tuple<T, T> t1, Tuple<T, T> t2) { return _cmp(t1.Item1, t2.Item1) && _cmp(t1.Item2, t2.Item2); } public int GetHashCode(Tuple<T, T> t) { return _cmp.GetHashCode(t.Item1) ^ _cmp.GetHashCode(t.Item2) } } 

and then

 var myList = myEF.GroupBy(e => new Tuple<String, String>(e.Code, e.Description), new StructuralTupleComparer(StringComparer.InvariantCultureIgnoreCase)) .Select(e => e.First()) .ToList(); 

and hope that at some point in the glorious future there will be a method for extending static IGrouping GroupBy<T, U>(this IEnumerable<T> src, Func<T, U> groupingprojection, Func<U, bool> equalitytester) (for Great justice)

0
source

Source: https://habr.com/ru/post/1203492/


All Articles