分组列表< string>在c#中类似的类型 [英] grouping list<string> of similar type in c#

查看:100
本文介绍了分组列表< string>在c#中类似的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  .GroupBy(x => x)

.GroupBy用于对类似类型的字符串,整型等进行分组。
然后我可以使用什么功能来分组List<相似类型的字符串>。 依赖于实现 > Equals / GetHashCode 以适合您的目的。 您的问题isn不清楚,但我的猜测是,你想要两个具有相同元素的列表被认为是平等的。我怀疑你需要编写你自己的 IEqualityComparer 实现,并将它传递给 GroupBy 。例如(未测试):

  public class ListEqualityComparer< T> :IEqualityComparer< List< T>> 
{
private static readonly EqualityComparer< T> ElementComparer =
EqualityComparer< T> .Default;
$ b $ public int GetHashCode(List< T> input)
{
if(input == null)
{
return 0;
}
//可以使用Aggregate for this ...
int hash = 17;
foreach(输入中的T项)
{
hash = hash * 31 + ElementComparer.GetHashCode(item);
}
返回散列;

$ b $ public bool Equals(List first,List< T> second)
{
if(first == second)
{
返回true;
}
if(first == null || second == null)
{
return false;
}
返回first.SequenceEqual(second,ElementComparer);


$ / code>

您也可以允许每个 ListEqualityComparer 实例具有单独的每元素比较器,这将允许您以不区分大小写的方式比较(说)字符串列表。


.GroupBy(x => x) 

.GroupBy is used to group string,int,etc of similar types. Then what function can i use to group List< string> of similar type.

解决方案

GroupBy relies on the element type implementing Equals/GetHashCode in an appropriate way for your aim.

Your question isn't clear, but my guess is that you want two lists with the same elements to be considered equal. I suspect you'll need to write your own IEqualityComparer implementation, and pass that into GroupBy. For example (untested):

public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
    private static readonly EqualityComparer<T> ElementComparer =
        EqualityComparer<T>.Default;

    public int GetHashCode(List<T> input)
    {
        if (input == null)
        {
            return 0;
        }
        // Could use Aggregate for this...
        int hash = 17;
        foreach (T item in input)
        {
            hash = hash *31 + ElementComparer.GetHashCode(item);
        }
        return hash;
    }

    public bool Equals(List<T> first, List<T> second)
    {
        if (first == second)
        {
            return true;
        }
        if (first == null || second == null)
        {
            return false;
        }
        return first.SequenceEqual(second, ElementComparer);
    }
}

You could also allow each ListEqualityComparer instance to have a separate per-element comparer, which would allow you to compare (say) lists of strings in a case-insensitive fashion.

这篇关于分组列表&lt; string&gt;在c#中类似的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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