Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Linq Lambda函数将可为空的十进制数和百分比相加 更新。。_C#_Linq_Lambda - Fatal编程技术网

C# 使用Linq Lambda函数将可为空的十进制数和百分比相加 更新。。

C# 使用Linq Lambda函数将可为空的十进制数和百分比相加 更新。。,c#,linq,lambda,C#,Linq,Lambda,我是这么要求的 我有一份声明。FOR语句通过reportList生成。reportList对象是设置为数据库中特定视图的列表类型 FOR循环遍历报告列表并创建报告。在报告的末尾,我必须从一个可为空的十进制值中输出一个百分比 for (int i = 0; i < reportList.Count() - 1; i++) { print report totals... lastly print percentage... htw.Write(reportList.Whe

我是这么要求的

我有一份声明。FOR语句通过reportList生成。reportList对象是设置为数据库中特定视图的列表类型

FOR循环遍历报告列表并创建报告。在报告的末尾,我必须从一个可为空的十进制值中输出一个百分比

for (int i = 0; i < reportList.Count() - 1; i++)
{

   print report totals...
   lastly print percentage...
   htw.Write(reportList.Where(x => x.Name == reportList[i].Name && x == reportList[i].Value).Select(a => a.RequiredValue == null ? 0 : a.RequiredValue).Sum(a => a.Value * 100));
   }
说到这里,我的问题是,这是使用Linq和Lambda输出百分比的最佳方法吗?有没有我不用的接线员?需要这笔钱吗?我只需要将一个小数转换成一个百分比,并考虑空值。

试试这个:

reportList.Select(g => g.X ?? 0).Sum();
或:


不要执行列表中的
FirstOrDefault()
。这意味着只对列表中的第一个元素执行
求和操作。您也可以使用操作符-
g.X??0
相当于
g.X==null?0:g.X
@Caleb你推荐我用什么?谢谢,我会试一试的。
reportList.Select(g => g.X ?? 0).Sum();
reportList.Select(g => g.X == null ? 0 : g.X * 100).Sum();