将字符串添加到List <list <string>&gt; </list <string> </string>内的List <string>

时间:2013-08-19 21:28:41

标签: c# list

我试图将一个字符串对象添加到列表中的列表&gt;在for&amp; while循环,尝试使用var i作为我希望使用的列表对象。

这是该类的代码,对于我做错的任何帮助将非常感激:)

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
                 }
             }
        }

4 个答案:

答案 0 :(得分:0)

你是对的,有了错误,你需要了解

  

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);

答案 1 :(得分:0)

尝试使用File.ReadAllLines()。将for循环替换为:

foreach(var file in filesToRead) {
  _toLoad.Add(File.ReadAllLines(file).ToList());
}

答案 2 :(得分:0)

你可以使用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> s为我们自动。

答案 3 :(得分:0)

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);
             }
         }
    }