首页 > 解决方案 > 是否可以对列表中的所有整数求和?(C# 控制台)

问题描述

我有一个包含用户输入值的列表。我希望输入的所有整数最后加在一起并显示总数。这可能吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            List<int> price= new List<int>();
        enterprice:
            Console.WriteLine("Please enter price");
            Console.WriteLine("When Finished please press '/'");
            string pricex = Console.ReadLine();

            if (pricex == "/")
            {
                goto receipt;
            }
            else
            {               
                int pricey = Convert.ToInt16(pricex);
                price.Add(pricey);
                Console.Clear();
                goto enterprice;
            }

        receipt:
            Console.Clear();
            Console.WriteLine("Your Outflows:");
            Console.WriteLine(string.Join("\n", price));
            Console.ReadKey();
        }
    }
}

在任何人提到之前,我知道有比 goto 更好的方法,我可能可以将用户输入的数据直接保存为整数,我将学习如何但刚刚开始,所以想慢慢来。非常感谢 ;)

标签: c#

解决方案


List 对象上有一个 sum 函数。

var total = price.Sum();

它是 System.Linq 上的扩展方法。所以,你也需要。

using System.Linq;

推荐阅读