【问题标题】:Total sum for an object property value in a list using a lambda function [duplicate]使用 lambda 函数的列表中对象属性值的总和 [重复]
【发布时间】:2012-05-06 04:24:32
【问题描述】:

我有以下内容:List<OutputRow>,其中包含许多 OutputRow 对象。

我想知道是否有办法让我在列表中使用 lambda 函数来返回列表中每个 OutputRow 对象上某个 propertyX 的值的总和。

示例列表:

OutputRow.propertyX = 4  
OutputRow.propertyX = 6  
OutputRow.propertyX = 5  

返回 15

【问题讨论】:

    标签: c# list properties lambda


    【解决方案1】:

    测试数据

    var ls=new List<OutputRow>();
    ls.Add(new OutputRow(){propertyX=4});
    ls.Add(new OutputRow(){propertyX=6});
    ls.Add(new OutputRow(){propertyX=5});
    

    Lambda

    var total= ls.Sum(x=>x.propertyX);
    

    【讨论】:

    • 完美运行,正是我所需要的!谢谢。
    【解决方案2】:

    类似这样的:

    var yourSum = yourOutputRowList.Sum(x => x.propertyX);
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2020-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      相关资源
      最近更新 更多