简体   繁体   English

使用文件读取将整数添加到列表或数组

[英]Add integers to a list or array with filereading

I have a .txt file with some numbers 我有一个带有一些数字的.txt文件

File:
1
2
3
4

I would like to have a method that reads those numbers and adds them to a list or array which will show it in a messagebox. 我希望有一种方法可以读取这些数字并将其添加到将在消息框中显示的列表或数组中。

I have this at the moment: 我现在有这个:

public void LaadVrijeKamers()
        {
            int KamerNummers = Convert.ToInt32(File.ReadAllText(@"x\Vrijekamers.txt"));
            MessageBox.Show(Convert.ToString(KamerNummers));
        }

I am getting an error in Dutch that says the following: 我在荷兰语中收到一条错误消息,内容如下:

Can not read the characters

I think the File.ReadAllText is only for Strings, but I am not sure. 我认为File.ReadAllText仅适用于字符串,但我不确定。 Maybe I am converting wrong. 也许我转换错了。

尝试逐行阅读并将字符串转换为整数:

var numbers = File.ReadLines(@"C:\path\numbers.txt").Select(int.Parse).ToList();

File.ReadAllLines() returns an array of strings. File.ReadAllLines()返回字符串数组。 Convert.ToInt32 takes a single string. Convert.ToInt32采用单个字符串。

You need to iterate over each string in the file and convert them one at a time. 您需要遍历文件中的每个字符串,然后一次将它们转换一次。

File.ReadAllText fails because it returns all the text, which is not convertible to an integer. File.ReadAllText失败,因为它返回所有文本,该文本不能转换为整数。 You should try something like the following: 您应该尝试如下操作:

int intList = File.ReadAllLines()
                  -- get only lines with numbers
                  .Where(l => {
                      int val;
                      bool isOk = int.TryParse(l, out value);
                      return isOk;
                  }
                  -- actual conversion
                  .Select(l => Convert.ToInt32(l)
                  .ToList();

Well, you can use a combination of LINQ methods here : 好了,您可以在这里结合使用LINQ方法:

    public void LaadVrijeKamers()
    {
        var KamerNummers =    File.ReadAllLines(@"x\Vrijekamers.txt")
                              .Skip(1)                      //Skips file header (if needed)
                              .Select(Int32.Parse)          //Converts to int
                              .ToList();                    //Returns List

        // To display numbers we'd first have to create a string from our list
        MessageBox.Show(string.Concat(KamerNummers.Select(n => n.ToString() + ", ")));
    }

Without Linq query 没有Linq查询

var rows = File.ReadAllText(@"x\Vrijekamers.txt");
var strnumbers = rows.Split(new string[] { "\r\n" }, StringSplitOptions.None);

var ListOfNumber = new List<int>();

foreach (string number in strnumbers)
{
    int num = 0;

    if(int.TryParse(number, out num))
        ListOfNumber.Add(num);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM