c# - linq中varchar字段的和,如何进行转换

标签 c# linq

我有一个sql查询

select SUM(convert(numeric ,Sub_Key_Value)) from [dbo].[Business_Report] where Parent_Tab='Staffing' and Sub_Key_Name='BM'

它运行良好,我正在尝试使用 c# 中的 linq 来实现它, 下面是代码

int sum = dt.AsEnumerable().Where(x => x.Field<string>("Parent_Tab") == "Staffing")
                           .Where((y => y.Field<string>("Sub_Key_Name") == "BM")).Sum(z => z.Field<int>("Sub_Key_Value"));

问题是,当我运行此代码时,它显示“指定的转换无效。”可能在部分

Sum(z => z.Field<int>("Sub_Key_Value")

它是来自数据库的字符串,无法将其转换为 int 来获取总和
任何关于如何在 linq 中获取总和的想法都是值得赞赏的谢谢

最佳答案

因为 Field 不会转换为 int

int sum = dt.Rows.Cast<DatRow>().Sum(r => "Staffing".Equals(r["Parent_Tab"]) 
              && "BM".Equals(r["Sub_Key_Name"]) ? Convert.ToInt32(r["Sub_Key_Value"]) : 0);

关于c# - linq中varchar字段的和,如何进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975867/

相关文章:

c# - 从 linq 查询调用函数时出错

c# - 有人可以滥用 LINQ 来解决这个金钱难题吗?

C# 正则表达式可选命名组

c# - Selenium WebDriver 超时异常

c# - 我可以在面向 .Net 3.5 的项目中使用所有 C# 4.0 功能吗?

C# MVC/API - 从 Amazon S3 为我的 API 调用返回图像

C# Automapper IQueryable - LINQ 2 SQLite - 查询仅返回父项,嵌套子项始终为 null

linq - WCF 数据服务、DTO 和 Entity Framework : The argument to DbIsNullExpression must refer to a primitive, 枚举或引用类型

c# - 可查询的混淆

c# - 将 "2.45"转换为十进制