如何使用条件和linq C# [英] how to use conditional sum linq c#

查看:71
本文介绍了如何使用条件和linq C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么了?如何正确过滤出负面因素?

  class程序{静态void Main(string [] args){int [] array = {1,2,-3,4,5,-1,4,-2};double sumOfElem = array.Sum(element =>元素< 0);Console.WriteLine(sumOfElem);}} 

解决方案

我认为您需要这个:

  double sumOfElem = array.Sum(element =>(element< 0?0:element)); 

这样,您将使用 Sum 的重载,该重载利用了转换函数(即所谓的 selector ),该函数应用于数组的每个元素.>

上面的代码过滤掉了元素.如果要过滤出阳性,则只需对比较运算符求逆:

  double sumOfElem = array.Sum(element =>(element> 0?0:element)); 

What is wrong here? How to filter out negative elements correctly?

class Program
{
    static void Main(string[] args)
    {
         int[] array = { 1, 2, -3, 4, 5, -1, 4, -2 };

         double sumOfElem = array.Sum(element => element < 0);
         Console.WriteLine(sumOfElem);
    }
}

解决方案

I think you need this:

double sumOfElem = array.Sum(element => (element < 0 ? 0 : element));

This way you are using an overload of Sum that utilises a transform function (so called selector), that is applied to each element of the array.

The above filters out negative elements. If you want to filter out positive ones, then simply inverse the comparison operator:

double sumOfElem = array.Sum(element => (element > 0 ? 0 : element));

这篇关于如何使用条件和linq C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆