Is there anyway to do a LINQ2SQL query doing something similar to this:
var result = source.GroupBy(a => new { a.Column1, a.Column2 });
or
var result = from s in source
group s by new { s.Column1, s.Column2 } into c
select new { Column1 = c.Key.Column1, Column2 = c.Key.Column2 };
but with ignoring the case of the contents of the grouped columns?
I had the same issue grouping by the values of DataRow objects from a Table, but I just used .ToString() on the DataRow object to get past the compiler issue, e.g.
instead of
You can pass
StringComparer.InvariantCultureIgnoreCase
to theGroupBy
extension method.Or you can use
ToUpperInvariant
on each field as suggested by Hamlet Hakobyan on comment. I recommendToUpperInvariant
orToUpper
rather thanToLower
orToLowerInvariant
because it is optimized for programmatic comparison purpose.I couldn't get NaveenBhat's solution to work, getting a compile error:
To make it work, I found it easiest and clearest to define a new class to store my key columns (GroupKey), then a separate class that implements IEqualityComparer (KeyComparer). I can then call
The KeyComparer class does compare the strings with the InvariantCultureIgnoreCase comparer, so kudos to NaveenBhat for pointing me in the right direction.
Simplified versions of my classes:
I've expanded on Bill B's answer to make things a little more dynamic to avoid "hardcoding" the column properties in the
GroupKey
andIQualityComparer<>
.Usage:
This way, you can pass any number of columns into the
GroupKey
constructor.