c# - 使用 LINQ 聚合对象

标签 c# entity-framework-4 linq-to-entities

我有 SQL 查询来获取 block 的数量,按 block 名称分组

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"

最佳答案

尝试一下:

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

聚合参数说明:

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

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

关于c# - 使用 LINQ 聚合对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15829071/

相关文章:

c# - 如何在 xamarin 中获取 ip 网络连接版本(是 IPv4 还是 IPv6)?

c# - 如何在 visual studio 中获取文件的相对路径?

entity-framework - 从数据库更新模型时,为什么设计人员会创建两个.Designer.cs文件?

c# - LINQ 中的 First() 会导致急切加载还是延迟加载?

c# - 如何在 Entity Framework 中结合 inner join 和 left join

Linq toEntity - 在 EntityCollection 导航属性中搜索

c# - Windows 服务中的可重入计时器

C# MySQL 事务提交

stored-procedures - EF中存储过程的输出参数

c# - 建议在 Entity Framework 4 中使用临时表或表变量。更新性能 Entity Framework