将字符串添加到列表<;字符串>;在列表内部<;列表<;字符串>>;
本文关键字:lt 字符串 列表 gt 内部 添加 | 更新日期: 2023-09-27 18:28:19
我试图在for&while循环,尝试使用vari作为我希望使用的列表对象。
这是课程的代码,如果能帮助我做错事,我们将不胜感激:)
public class GenClass
{
private static int _genCount;
private static bool _filesLoadedToLists;
private static List<string> _nounSetOne = new List<string>();
private static List<string> _nounSetTwo = new List<string>();
private static List<List<string>> _toLoad = new List<List<string>>();
private string _emotionMidTrim = "";
public const string FileOne = "NounSetOne.txt";
public const string FileTwo = "NounSetTwo.txt";
public GenClass()
{
while (_filesLoadedToLists == false)
{
TextToList(FileOne,FileTwo);
_filesLoadedToLists = true;
}
_genCount++;
}
问题出在类的这一部分
public void TextToList(string fileOne, string fileTwo)
{
List<string> filesToRead = new List<string>();
filesToRead.Add(fileOne); // Add the text files to read to a list
filesToRead.Add(fileTwo); // Add the text files to read to a list
_toLoad.Add(_nounSetOne); // Add a list of words to this list
_toLoad.Add(_nounSetTwo); // Add a list of words to this list
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i.Add(line)]; // the error is here
}
}
}
尝试使用File.ReadAllLines()。将for循环替换为:
foreach(var file in filesToRead) {
_toLoad.Add(File.ReadAllLines(file).ToList());
}
您是正确的,有了错误,您需要了解
List<List<string>>
将取一个List<string>
,而不是一个字符串
试试这样的东西;
List<string> listOfString = new List<string>;
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
listOfString.add(line);
}
}
}
然后,
_toLoad.add(listOfStrings);
使用LINQ:可以大大减少这种情况
List<string> filesToRead = new List<string> {"NounSetOne.txt", "NounSetTwo.txt"};
List<List<string>> _toLoad = new List<List<string>>();
_toLoad.AddRange(filesToRead.Select(f => File.ReadAllLines (f).ToList() ));
请注意,文件名没有多余的变量(如果它们的唯一目的是添加到列表中,为什么要使用FileOne/FileTwo?)并且我们让AddRange负责自动为我们创建List<string>
。
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i].Add(line);
}
}
}