Linq删除重复忽略大小写

时间:2017-12-17 14:14:55

标签: c# asp.net asp.net-mvc linq asp.net-mvc-4

我有像这样的示例列表数据

  

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

我想从该列表中删除重复项并获取新列表。 我的代码:

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

但它返回

  

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

如何摆脱那种不同的情况?就像excel中的过滤系统一样只能获得1个Apple。

3 个答案:

答案 0 :(得分:2)

server接受GroupBy的实现,StringComparer实现它并提供标准的预配置选项:

IEqualityComparer<T>

有多种选择,包括a.GroupBy(x => x, StringComparer.OrdinalIgnoreCase).Select... CurrentCultureIgnoreCaseInvariantCultureIgnoreCase

更多详情:https://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase(v=vs.110).aspx

答案 1 :(得分:0)

这将根据套管过滤它:

// using System.Linq;

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

如果你想在不尊重套管的情况下得到它们:

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));
    }
}

输出(区分大小写):

Apple,WaterMelon,ApplE,APple

输出(不敏感):

WaterMelon

答案 2 :(得分:-1)

您可以使用字典将字符串添加为键,将字符串添加为值。

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;