c# - 是否可以对列表中的所有整数求和?(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 更好的方法,我可能可以将用户输入的数据直接保存为整数,我将学习如何但刚刚开始,所以想慢慢来。非常感谢 ;)
解决方案
List 对象上有一个 sum 函数。
var total = price.Sum();
它是 System.Linq 上的扩展方法。所以,你也需要。
using System.Linq;
推荐阅读
- swift - TabView 项目点击滚动到它的 NavigationView 顶部
- python - FastAPI:如何将任意属性 dict 映射到 pydantic 模型以让 swagger 显示细节
- java - java.io.FileNotFoundException:/opt/tomcat/conf/tomcat-users.xml(打开的文件太多)
- r - stat_cor:显示 r 值、p 值和显着性(***、**、*)
- javascript - 如何更改开发位置?
- python - 计算分位数的差异
- reactjs - React Native 视频最终出现白屏并且应用程序没有响应
- javascript - 如何发送位于另一个文件中的嵌入?
- ldap - OpenLDAP 副本在同步时跳过几个项目的原因可能是什么
- javascript - 名称中有空格的反应本机图像未加载