Thomas
Thomas

Reputation: 12107

Remove duplicate strings in list using C# / LinQ but ignore case

With the list:

"A", "Bb", "C", "a", "d", "bb"

How can I use LinQ to remove duplicates while ignoring casing?

the output here should be:

"C", "d"

Upvotes: 0

Views: 2415

Answers (3)

D. Macdonald
D. Macdonald

Reputation: 1

You can use GroupBy() with the StringComparer.CurrentCultureIgnoreCase option as follows:

List<String> data = new List<String>() { "A", "Bb", "C", "a", "d", "bb" };
List<String> newData = data.GroupBy(x => x, StringComparer.CurrentCultureIgnoreCase)
    .Where(el => el.Count() == 1)
    .Select(el => el.Key)
    .ToList();

Upvotes: 0

Sooriya Dasanayake
Sooriya Dasanayake

Reputation: 1156

try this

  var result = testList
               .GroupBy(item => item, StringComparer.OrdinalIgnoreCase)
               .Where(g => g.Count() == 1)
               .Select(g => g.Key)
               .ToList();

Upvotes: 8

Klaus G&#252;tter
Klaus G&#252;tter

Reputation: 11997

Use can use the GroupBy method with one of the IgnoreCase string comparers, then select only those groups consisting of a single element

.GroupBy(_ => _, StringComparer.CurrentCultureIgnoreCase)
.Where(_ => _.Count() == 1)

Upvotes: 2

Related Questions