GroupBy multidimensional from an array of Int

I have this multidimensional array:

int[][] x;

So, for each position, I have:

x[0] = [10,10,10,10,10]
x[1] = [10,10,10,10,10]
x[2] = [10,10,10,10,10]
x[3] = [5,5,5]
x[4] = [5,5,5]
x[5] = [10,5,5,5]
x[6] = [10,5,5,5]
x[7] = [5,5,5]

I need a group:

z[0] = 3 x [10,10,10,10,10]
z[1] = 3 x [5,5,5]
z[2] = 2 x [10,5,5,5]

Or, if possible:

y[0] = 3 | 5x10
y[1] = 3 | 3x5 
y[2] = 2 | 1x10, 3x5
+4
source share
1 answer

Well, C # LINQ has .Distinct()an extension method that returns a list of individual elements. The problem is that two arrays are not considered equal if they have the same elements (in the same order). Therefore, you must first create IEqualityComparer<T>:

public class ArrayEqual<T> : IEqualityComparer<T[]> {

    public bool Equals(T[] x, T[] y) {
        return Enumerable.SequenceEqual(x,y);
    }

    public int GetHashCode (T[] x) {
        int hash = 0;
        foreach(T t in x) {
            hash = 3*hash ^ t.GetHashCode();
        }
        return hash;
    }

}

And then name it with:

int[][] z = x.Distinct(new ArrayEqual<int>()).ToArray();

If you want to generate count tuples with an array, you can do this with

Tuple<int,int[]>[] z = x.GroupBy(x => x,new ArrayEqual<int>()).Select(x => new Tuple<int,int[]>(x.Count(),x.Key)).ToArray();

Enumerable.SequenceEqual . GetHashCode, , , , . , .

+5

All Articles