You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LINQPad中计算results.parent1总和并通过Console.Write输出?

问题描述

我正在使用LINQPad,已编写代码筛选出child1为true的parent对象集合results。当前使用Dump方法可将结果以表格形式展示,但我希望通过Console.Write输出该集合中所有元素的parent1属性的总和,请问该如何实现?

原代码如下:

void Main()
{
    List<parent> a = new List<parent>();
    a.Add(new parent(2, true));

    a.Add(new parent(3, false));
    a.Add(new parent(4, true));

    List<parent> results = a.FindAll(
    delegate (parent p)
    {
        return p.child1 == true;
    });
    if (results.Count > 0)
    {
        //how do i find the sum of all the results.parent1?
        results.Dump();
        Console.Write("sum of all the results.parent1? ");
    }
}
/// <summary>
/// This file holds all user defined indicator methods.
/// </summary>
public class parent
{
    int v;

    public parent(double d, bool b)
    {
        this.parent1 = d;
        this.child1 = b;
    }

    public double parent1 { get; set; }

    public bool child1 { get; set; }
}
解决方案

你可以直接使用LINQ的Sum扩展方法计算results集合中所有元素parent1属性的总和,修改后的代码如下:

void Main()
{
    List<parent> a = new List<parent>();
    a.Add(new parent(2, true));

    a.Add(new parent(3, false));
    a.Add(new parent(4, true));

    List<parent> results = a.FindAll(
    delegate (parent p)
    {
        return p.child1 == true;
    });
    if (results.Count > 0)
    {
        results.Dump();
        // 计算总和并输出
        double total = results.Sum(p => p.parent1);
        Console.Write($"sum of all the results.parent1? {total}");
    }
}
/// <summary>
/// This file holds all user defined indicator methods.
/// </summary>
public class parent
{
    int v;

    public parent(double d, bool b)
    {
        this.parent1 = d;
        this.child1 = b;
    }

    public double parent1 { get; set; }

    public bool child1 { get; set; }
}

额外优化建议

如果不需要保留筛选后的集合results,可以直接将筛选和求和合并为一步,简化代码:

void Main()
{
    List<parent> a = new List<parent>();
    a.Add(new parent(2, true));
    a.Add(new parent(3, false));
    a.Add(new parent(4, true));

    double total = a.Where(p => p.child1).Sum(p => p.parent1);
    Console.Write($"sum of all the results.parent1? {total}");
    // 若仍需展示筛选结果,单独调用Dump即可
    a.Where(p => p.child1).Dump();
}

内容的提问来源于stack exchange,提问作者junkone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:10:34