简体   繁体   English

分组列表<string> c# 中的类似类型</string>

[英]grouping list<string> of similar type in c#

.GroupBy(x => x) 

.GroupBy is used to group string,int,etc of similar types. .GroupBy 用于对类似类型的字符串、整数等进行分组。 Then what function can i use to group List< string> of similar type.那么我可以用什么 function 来对类似类型的 List<string> 进行分组。

GroupBy relies on the element type implementing Equals / GetHashCode in an appropriate way for your aim. GroupBy依赖于以适当方式实现Equals / GetHashCode的元素类型来实现您的目标。

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 .我怀疑您需要编写自己的IEqualityComparer实现,并将其传递给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.您还可以允许每个ListEqualityComparer实例具有单独的每个元素比较器,这将允许您以不区分大小写的方式比较(例如)字符串列表。

I assume you are asking how to group by objects of custom type.我假设您正在询问如何按自定义类型的对象进行分组。

You need to define how your objects should be compared to each other.您需要定义您的对象应如何相互比较。
You can do this by specifying IEqualityComparer in the GroupBy call.您可以通过在GroupBy调用中指定IEqualityComparer来做到这一点。

If you don't specify IEqualityComparer , then IEqualityComparer.Default is used, which checks whether type T implements the System.IEquatable<T> interface and, if so, returns an EqualityComparer<T> that uses that implementation.如果您不指定IEqualityComparer ,则使用IEqualityComparer.Default ,它检查类型T是否实现了System.IEquatable<T>接口,如果是,则返回使用该实现的EqualityComparer<T> Otherwise, it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T .否则,它返回一个EqualityComparer<T> ,它使用T提供的 Object.Equals 和 Object.GetHashCode 的覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM