我有一张桌子
ID|VALUE
VALUE 是一个整数字段,可能的值在 0 到 4 之间。如何查询每个值的计数?
理想情况下,结果应该是一个包含 6 个元素的数组,其中一个元素表示每个值的计数,最后一个元素表示总行数。
这个简单的程序就是这样做的:
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();
以下是如何获取每个
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() });
int[] x = { 1, 1, 2, 2, 3, 5, 5, 5 };
var z = x.GroupBy(a => a).Select(a => a.First() + "," + a.Count());
foreach (var i in z)
{
Console.WriteLine(i);
}