GroupBySequence

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
					
public class Program
{
    public class SequenceComparer : IEqualityComparer<string[]>
    {
        public bool Equals(string[] x, string[] y)
        {
            if (ReferenceEquals(x, y))
                return true;
            if (x == null || y == null)
                return false;
            return x.SequenceEqual(y);
        }

        public int GetHashCode(string[] obj)
        {
            return obj.Aggregate(42, (c, n) => c ^ n.GetHashCode());
        }
    }

	public static void Main()
	{
        var json = "[\r\n    {\r\n        \"product\": [\r\n                   \"a\", \"b\", \"c\"\r\n                  ]\r\n    },\r\n    {\r\n        \"product\": [\r\n                  \"a\",\"b\"\r\n                  ]\r\n    },\r\n    {\r\n        \"product\": [\r\n                   \"b\",\"c\"\r\n                 ]\r\n    },\r\n    {\r\n       \"product\": [\r\n                   \"b\", \"c\"\r\n                ]\r\n    },\r\n    {\r\n        \"product\": [\r\n                  \"a\",\"b\"\r\n                  ]\r\n    },\r\n    {\r\n       \"product\": [\r\n                   \"b\", \"c\"\r\n                ]\r\n    },\r\n    {\r\n        \"product\": [\r\n                  \"a\"\r\n                  ]\r\n    },\r\n]";


        var products = JsonConvert.DeserializeAnonymousType(json, new[] {new {product = new string[] { }}});
        var result = products.GroupBy(p => p.product, new SequenceComparer())
            .Select(g => new {g.Key, Count = g.Count()})
            .OrderByDescending(x => x.Count)
            .Take(3);

        foreach (var row in result)
            Console.WriteLine("'{0}' {1}", string.Join(",", row.Key), row.Count);

	}
}
;