2

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.

5
  • What is the lstMyList class definition? Commented Mar 31, 2014 at 5:12
  • Having a key that is an int[] is probably not going to work for you. We need the class definition. Commented Mar 31, 2014 at 5:13
  • declare lstMyList List<int[]> lstMyList = new List<int[]>(); or List<Array> lstMyList = new List<Array>(); Commented Mar 31, 2014 at 5:13
  • If you have two int arrays - both int[] { 1, 2 } - they are not equal to each other using standard equality as arrays are reference types and they only compare if the array is the same reference. Two arrays, even with the same values, are different. Commented Mar 31, 2014 at 5:16
  • See about Enumerable.GroupBy Method with IEqualityComparer<TKey> Commented Mar 31, 2014 at 5:22

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

It should be noted that this solution does have some potential drawbacks. The g.Key will be a reference to one of the "equal" arrays so careful if you modify the contents. Also the comparer will not equate {1,2} & {2,1} so, depending what the domain logic is, this could be an issue too.
0

Try this

var group = lstMyList.GroupBy(t => t,
              StructuralComparisons.StructuralEqualityComparer).ToArray();

2 Comments

I try but receive error: has some invalid arguments
Apologies. You might want to take a look at this for the fix stackoverflow.com/a/5601068/1808494

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.