views:

93

answers:

2

I have a table

ID|VALUE

VALUE an integer field with possible values 0 - 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.

+1  A: 

Here is how you would get the number of rows for each value of VALUE, in order:

var counts =
    from row in db.Table
    group row by row.VALUE into rowsByValue
    orderby rowsByValue.Key
    select rowsByValue.Count();

To get the total number of rows in the table, you can add all of the counts together. You don't want the original sequence to be iterated twice, though; that would cause the query to be executed twice. Instead, you should make an intermediate list first:

var countsList = counts.ToList();   

var countsWithTotal = countsList.Concat(new[] { countsList.Sum() });
Bryan Watts
or can I just add all the counts? can i use counts.Sum()?
Rana
Yes, you could do that as well. I have edited my answer to reflect it.
Bryan Watts
+6  A: 

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();
Leniel Macaferi