c# - 我必须将列表中的数字添加到文件中
问题描述
这是我的代码,但每次我尝试编译它时,我都会收到此错误:
System.IndexOutOfRangeException:索引超出了数组的范围。
using System;
using System.Collections.Generic;
using System.IO;
namespace nrinfile
{
class Program
{
static void Main(string[] args)
{
List<int> numbers= new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
string[] folderLoc = File.ReadAllLines(@"E:\folder\numbers.txt");
for (int i = 0; i < 12; i++)
{
folderLoc[i] = Convert.ToString(numbers[i]);
}
}
}
}`
解决方案
不能保证至少folderLoc
有物品 _12
for (int i = 0; i < 12; i++) {...}
你可以这样写(注意folderLoc.Length
而不是12
):
string[] folderLoc = File.ReadAllLines(@"E:\folder\numbers.txt");
// If you want at most 12 items to be changed put the condition as
// i < Math.Max(12, folderLoc.Length)
for (int i = 0; i < folderLoc.Length; i++)
{
folderLoc[i] = $"{i} {folderLoc[i]}"; //TODO: Apply the correct format here
}
甚至(没有显式循环,但Linq查询)
using System.Linq;
...
string[] folderLoc = File
.ReadLines(@"E:\folder\numbers.txt")
.Select((value, index) => $"{index} {value}")
.ToArray();
如果您只想更改顶12
行,则应该Select
是
...
.Select((value, index) => index < 12 ? $"{index} {value}" : value)
...
最后,如果您只想将0..11
数字写入文件
File.WriteAllLines(@"E:\folder\numbers.txt", Enumerable.Range(0, 12));
推荐阅读
- java - Android FileObserver onEvent 不起作用
- python - numpy函数内的熊猫数据框分组操作
- google-sheets - 如何在 Google 表格中执行 SUMPRODUCT,但以两个向量中的文本为条件?
- python - 使用 ipyleaflet 保存 GeoJson / 访问标记列表
- excel - 如何复制(从 COL)和粘贴(到 ROW)(替换特定位置的数据)?
- git - 获取“env:bash\r:没有这样的文件或目录”我正在使用 Mac 终端并在执行 git commit 时遇到此问题
- sql - 大查询中的数组
- android - 排球没有提出要求
- javascript - 听按键并添加到输入表单
- ruby-on-rails - 运行脚本 Ruby on Rails