按多个键分组并忽略大小写 [英] Group by multiple keys and ignore case

查看:56
本文介绍了按多个键分组并忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试执行以下操作时,

When I try to do the following,

collection.GroupBy(item => new
                        {
                            item.Item1,
                            item.Item2,
                            item.Item3,
                            item.Item4
                        }, StringComparer.CurrentCultureIgnoreCase)

我收到一个错误,指出无法从用法中推断出参数类型,并尝试显式指定类型参数.

I get an error that the argument types cannot be inferred from the usage, and to try to specify the type arguments explicitly.

正确的语法是什么?

推荐答案

顾名思义, StringComparer 用于比较简单的字符串,而不是匿名类型.

As the name suggests, the StringComparer is for comparing simple strings, not anonymous types.

StringComparer :

代表使用特定大小写和基于区域性或顺序比较规则的字符串比较操作.

Represents a string comparison operation that uses specific case and culture-based or ordinal comparison rules.

要比较您的班级,您可以创建自己的比较器:

To compare your class, you can create your own comparer:

public class CustomComparer : IEqualityComparer<SomeClass>
{
    public bool Equals(SomeClass x, SomeClass y)
    {
        return String.Equals(x.Item1, y.Item1, StringComparison.CurrentCultureIgnoreCase)
               && String.Equals(x.Item2, y.Item2, StringComparison.CurrentCultureIgnoreCase)
               && String.Equals(x.Item3, y.Item3, StringComparison.CurrentCultureIgnoreCase);
    }

    public int GetHashCode(SomeClass obj)
    {
        return string.Concat(obj.Item1.ToLower(),
                             obj.Item2.ToLower(),
                             obj.Item3.ToLower()).GetHashCode();
    }
}

并在 GroupBy 中使用它:

var collection = new List<SomeClass>();

// populate collection

collection.GroupBy(item => item, new CustomComparer());

这应该可行,尽管您可能需要尝试一下.

That should work, although you may need to play around with it.

这篇关于按多个键分组并忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆