I know I can easily do this with some for loops, but wanted to see if there was a way to do it with fluent LINQ. I'm trying to find out how many of each sub-list I have.
I was looking at Enumerable.SequenceEqual
but couldn't get it working with GroupBy()
Say I have a List<List<int>
like this:
{
{1,2}
{2, 3, 4}
{1,2}
{1,3}
{1,2}
}
and I want to group it by equal lists, like so
{
<3, {1,2}>
<1, {2, 3, 4>
<1, {1,3}
}
You'd need to implement a IEqualityComparer<List<T>>
, which you can then pass into GroupBy
. For example:
public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> lhs, List<T> rhs)
{
return lhs.SequenceEqual(rhs);
}
public int GetHashCode(List<T> list)
{
unchecked
{
int hash = 23;
foreach (T item in list)
{
hash = (hash * 31) + (item == null ? 0 : item.GetHashCode());
}
return hash;
}
}
}
Then:
var counts = lists.GroupBy(x => x,
(key, lists) => new { List = key, Count = lists.Count() },
new ListEqualityComparer<int>());
See more on this question at Stackoverflow