Search code examples
c#sqllinqlinq-to-sql

Using LINQ to count value frequency


I have a table

ID|VALUE

VALUE is an integer field with possible values between 0 and 4. How can I query the count of each value?

Ideally the result should be an array with 6 elements, one for the count of each value and the last one is the total number of rows.


Solution

  • This simple program does just that:

    class Record
    {
        public int Id { get; set; }
        public int Value { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            List<Record> records = new List<Record>()
            {
                new Record() { Id = 1,  Value = 0},
                new Record() { Id = 2,  Value = 1 },
                new Record() { Id = 3,  Value = 2 },
                new Record() { Id = 4,  Value = 3 },
                new Record() { Id = 5,  Value = 4 },
                new Record() { Id = 6,  Value = 2 },
                new Record() { Id = 7,  Value = 3 },
                new Record() { Id = 8,  Value = 1 },
                new Record() { Id = 9,  Value = 0 },
                new Record() { Id = 10, Value = 4 }
            };
    
            var query = from r in records
                        group r by r.Value into g
                        select new {Count = g.Count(), Value = g.Key};
    
            foreach (var v in query)
            {
                Console.WriteLine("Value = {0}, Count = {1}", v.Value, v.Count);
            }
        }
    }
    

    Output:

    Value = 0, Count = 2
    Value = 1, Count = 2
    Value = 2, Count = 2
    Value = 3, Count = 2
    Value = 4, Count = 2
    

    Slightly modified version to return an Array with only the count of values:

    int[] valuesCounted  = (from r in records
                            group r by r.Value
                            into g
                            select g.Count()).ToArray();
    

    Adding the rows count in the end:

    valuesCounted = valuesCounted.Concat(new[] { records.Count()}).ToArray();