I am learning LINQ in C#. I have the following JSON data:
[ { "product": [ "a", "b", "c" ] }, { "product": [ "a","b" ] }, { "product": [ "b","c" ] }, { "product": [ "b", "c" ] }, { "product": [ "a","b" ] }, { "product": [ "b", "c" ] }, { "product": [ "a" ] }, ] I would like to perform a LINQ by grouping product over its count then order by descending and finally selecting the top 3.
How can I do that? In the result, I have to show the product and its count like below:
"b","c" 3 "a","b" 2 "a","b","c" 1 My current code is:
public class Product { public List<string> Name { get; set; } } string json = File.ReadAllText("products.json"); var products = JsonConvert.DeserializeObject<List<Product>>(json); var result = (from p in products .GroupBy(pt => pt.Name) .OrderByDescending(pt => pt.Count()) .SelectMany(pt => pt) select p).Take(3); But I am getting all 1 as count. Can you please help to correct the result? Thank you.