2

我有 SQL 查询来获取块数,按块名称分组

var sql = @"select count(*) [COUNT], o.NAME from WISH w
                            left join objects o on o.ID = w.[BLOCKID]
                            where w.ISDELETE = 0
                            group by o.NAME"
var cmd = new SqlCommand(sql, connection);
var reader = cmd.ExecuteReader();
Label labelClear = (Label)Master.FindControl("labelClear");

if (reader.HasRows)
{
   while (reader.Read())
   {
      labelClear.Text += reader["NAME"].ToString() + " - " + reader["COUNT"].ToString() + "; ";
   }
 }

这使得输出字符串如下:

"BLOCKNAME1 - 15; BLOCKNAME2 - 3; BLOCKNAME3 - 28" etc.

(其中 15、3 和 28 - BLOCKNAME1、BLOCKNAME2 和 BLOCKNAME3 的计数)。

我尝试将此查询转换为 LINQ:

((Label)Master.FindControl("labelClear")).Text = 
Db.WISH.Where(x => x.ISDELETE == 0)
.GroupBy(x => x.OBJECTS_BLOCK.NAME)
.Select(g => new { Name = g.Key, Cnt =  SqlFunctions.StringConvert((decimal?)g.Count()) })
.Aggregate((a, b) => a.Name + ": " + a.Cnt + ", " + b.Name + ": " + b.Cnt );

但是在最后一行出现错误(使用聚合):

Cannot implicitly convert type 'string' to 'AnonymousType#2'

将结果聚合成字符串的正确方法是什么

"BLOCKNAME1 - 15; BLOCKNAME2 - 3; BLOCKNAME3 - 28"
4

1 回答 1

4

试试那个:

((Label)Master.FindControl("labelClear")).Text = 
Db.WISH.Where(x => x.ISDELETE == 0)
.GroupBy(x => x.OBJECTS_BLOCK.NAME)
.Select(g => new { Name = g.Key, Cnt =  SqlFunctions.StringConvert((decimal?)g.Count()) })
.AsEnumerable()
.Aggregate(string.Empty, (a, b) => a + ", " + b.Name + ": " + b.Cnt, s => s.Substring(2));

参数说明Aggregate

  • string.Empty- 初始种子值
  • (a, b) => a + ", " + b.Name + ":" + b.Cnt- 聚合函数。它将当前种子值与新值字符串连接起来。
  • s => s.Substring(2)- 结果选择功能。删除前 2 个字符,这是不必要的,

AsEnumerable将字符串连接从数据库移动到应用程序是必要的。EF 不支持Aggregate带有该参数的方法。Count()仍由 DB 执行。

于 2013-04-05T09:04:25.323 回答