Reputation: 23
I have an List<Array>
, I'm using LINQ to find duplicates and count, but it's not work.
See the image you can see, lstMyList[0] and lstMyList[11] have the same value in Int[]
Here is lstMyList definition:
List<Array> lstMyList = new List<Array>();
I used code, but it's not work:
var group = lstMyList.GroupBy(t => t).ToArray();
or
Dictionary<int[], int> count = lstMyList.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
Here is image: http://imageshack.com/a/img69/2552/h114.png
Maybe somebody can give me a hint about my problem.
Upvotes: 2
Views: 1360
Reputation: 12797
First create comparer class:
sealed class ArrayEqualityComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
if (x == null && y == null)
return true;
if (x != null && y != null)
return x.SequenceEqual(y);
return false;
}
public int GetHashCode(int[] obj)
{
return obj.Length;
}
}
Then you can use it in GroupBy clause.
List<int[]> lstMyList = new List<int[]> { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 1, 2 } };
var groups = lstMyList.GroupBy(t => t, new ArrayEqualityComparer())
.Select(g => new { g.Key, Count = g.Count() })
.ToArray();
Upvotes: 3
Reputation: 15772
Try this
var group = lstMyList.GroupBy(t => t,
StructuralComparisons.StructuralEqualityComparer).ToArray();
Upvotes: 0