Friday, January 9, 2009

Linq : Distinct and Case-Insensitive (StringComparer in action)

Recently, working on a project, and ran into a simple problem. Wanted to get distinct entries from a List (but this solution will work with any class that uses IEnumerable)

Basically, the requirement needed to make the distinct collection of strings be not case sensitive, so : FileName1 was equal to filename1 or Filename1

Looking at the great Distinct extension method for link, it exposes an overload to specify IEqualityComparer comparer.

Rather than looking around, or thinking about writing something, check out the StringComparer class.

You can specify a StringComparer:
StringComparer CurrentCulture { get; }
StringComparer CurrentCultureIgnoreCase { get; }
StringComparer InvariantCulture { get; }
StringComparer InvariantCultureIgnoreCase { get; }
StringComparer Ordinal { get; }
StringComparer OrdinalIgnoreCase { get; }

Here is the result:
var results= fileList.Distinct(StringComparer.CurrentCultureIgnoreCase);

So simple, and easy to use!

nested linq queries, how to get distinct values?

No comments: