Linq delete duplicate ignore case

I have example list data like this

var a = {Apple, Orange, WaterMelon, ApplE, Orange, APple}

I want to delete duplicates from that list and get a new list. My code :

var b = a.GroupBy(x => x).Where(y => y.Count() >= 1).Select(z => z.Key).ToList();

but it return

var b = {Apple, ApplE, APple, Orange, WaterMelon}

how to get rid of that different case? Like filtering system in excel that only get 1 Apple.

Upvotes: 2

Views: 317

Answers (3)

Bercovici Adrian
Bercovici Adrian

Reputation: 9360

You could use a dictionary that adds the string to lower as key and the string as value.

List<string> mylist = new List<string> { "app", "App", "zz", "zZ" };
            Dictionary<string, string> dict = new Dictionary<string, string>();
            string key = string.Empty;
            foreach(string c in mylist)
            {
                key = c.ToLower();
                if(!dict.Keys.Contains(key))
                {
                    dict.Add(key, c);
                }
            }
            var t = dict.Values;

Upvotes: -1

Patrick Artner
Patrick Artner

Reputation: 51653

This will filter it respecting casing:

// using System.Linq;

var a = new[]{"Apple", "Orange", "WaterMelon", "ApplE", "Orange", "APple"};
var b = a.Where(x => a.Count(i => i == x) == 1);

If you want to get them without respecting casing:

using System.Linq;
using System;

public class Program
{
    public static void Main()
    {
        var a = new[]{"Apple", "Orange", "WaterMelon", "ApplE", "Orange", "APple"};
        var b = a.Where(x => a.Count(i => i.Equals(x, StringComparison.OrdinalIgnoreCase )) == 1);

        System.Console.WriteLine(string.Join(",", b));
    }
}

Output (case sensitive):

Apple,WaterMelon,ApplE,APple

Output (insensitive):

WaterMelon

Upvotes: 0

jessehouwing
jessehouwing

Reputation: 114701

GroupBy accepts an implementation if IEqualityComparer<T>, StringComparer implements this and offer standard preconfigured options:

a.GroupBy(x => x, StringComparer.OrdinalIgnoreCase).Select...

There are multiple options available including CurrentCultureIgnoreCase, InvariantCultureIgnoreCase and OrdinalIgnoreCase.

More details: https://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase(v=vs.110).aspx

Upvotes: 2

Related Questions