C# 格式化列表中的值
在进入C#之前,我曾学习Python。我做了一个小项目,程序会列出一个列表,无论你键入什么,它都会添加到列表中。我试着在C#中做同样的练习,但我似乎在做一些事情,如果不是全部的话,因为这个程序不起作用。这是我的代码:C# 格式化列表中的值,c#,list,loops,formatting,C#,List,Loops,Formatting,在进入C#之前,我曾学习Python。我做了一个小项目,程序会列出一个列表,无论你键入什么,它都会添加到列表中。我试着在C#中做同样的练习,但我似乎在做一些事情,如果不是全部的话,因为这个程序不起作用。这是我的代码: 使用系统; 使用System.Collections.Generic: idk类 { 静态void Main(字符串[]参数) { 列表=新列表(); 因为(;真;) { 安慰。写下(“告诉我一些事情”); var inp=Console.ReadLine(); 列表。添加(inp
使用系统;
使用System.Collections.Generic:
idk类
{
静态void Main(字符串[]参数)
{
列表=新列表();
因为(;真;)
{
安慰。写下(“告诉我一些事情”);
var inp=Console.ReadLine();
列表。添加(inp);
var i=1;
foreach(列表中的字符串a)
var ni=i+1;
WriteLine(String.Format(“{0}.{1}”,ni,a));
}
}
}
因此,我希望我的程序接受输入,将其保存在列表中,然后以(例如)的形式打印列表
List=[]
尽管如此:
item=输入(“告诉我一些事情:”)
列表。追加(项目)
i=1
对于列表中的val:
打印(f“{i}.{val}”)
i+=1
我是否可以从我的代码中编辑一些东西,使它也能这样做?或者我可能需要重写整件事?谢谢您的帮助。我建议将循环类型从
foreach
更改为for
:
for (int i = 0; i < list.Count; ++i)
Console.WriteLine($"{i + 1}. {list[i]}");
您可以在Join
(加入列表项)和Linq(查询列表)的帮助下一次性打印列表:
我认为只有当用户决定不再输入任何内容时,才应在最后打印列表的内容:
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
List<string> strList = new List<string>();
while (true) {
Console.Write("Tell me something: ");
var str = Console.ReadLine();
if (String.IsNullOrWhiteSpace(str)) {
break;
}
strList.Add(str);
}
for (var i = 0; i < strList.Count; i++) {
Console.WriteLine(String.Format("{0}. {1}", i + 1, strList[i]));
}
}
}
试试看“这个程序不起作用”——怎么回事?它目前做什么?
for(inti=0;i程序无法工作,因为Console.WriteLine(String.Format(“{0}.{1}”,ni,a))代码>不编译,因为ni
被实例化并被丢弃,因为foreach
语句中缺少括号。注意:for(;true;)
有点不寻常<代码>while(true)
或(;;)
是更常见的无限循环版本
Console.WriteLine(string.Join(Environment.NewLine, list
.Select((value, index) => $"{index + 1}. {value}")));
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
List<string> strList = new List<string>();
while (true) {
Console.Write("Tell me something: ");
var str = Console.ReadLine();
if (String.IsNullOrWhiteSpace(str)) {
break;
}
strList.Add(str);
}
for (var i = 0; i < strList.Count; i++) {
Console.WriteLine(String.Format("{0}. {1}", i + 1, strList[i]));
}
}
}
Tell me something: idk
Tell me something: C
Tell me something: A
Tell me something:
1. idk
2. C
3. A