使用LINQ计算值频率

时间:2010-09-05 23:27:17

标签: c# sql linq linq-to-sql

我有一张桌子

ID|VALUE

VALUE是一个整数字段,可能的值介于0和4之间。如何查询每个值的计数?

理想情况下,结果应该是一个包含6个元素的数组,一个用于计算每个值,最后一个是总行数。

2 个答案:

答案 0 :(得分:17)

这个简单的程序就是这样:

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);
        }
    }
}

输出:

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

稍微修改后的版本,只返回一个只包含值的数组:

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

最后添加行数:

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

答案 1 :(得分:3)

以下是按顺序获取每个VALUE值的行数的方法:

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

要获取表格中的总行数,您可以将所有计数一起添加。但是,您不希望原始序列被迭代两次;这将导致查询执行两次。相反,您应该首先制作一个中间列表:

var countsList = counts.ToList();   

var countsWithTotal = countsList.Concat(new[] { countsList.Sum() });