grouping list<string> of similar type in c#
.GroupBy(x => x)
.GroupBy is used to gro开发者_如何学编程up 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.
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.
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. Otherwise, it returns an EqualityComparer<T>
that uses the overrides of Object.Equals and Object.GetHashCode provided by T
.
精彩评论