繁体   English   中英

将文件放入数组的最简单方法? - C#

[英]easiest way to take file into an array? - c#

我有一个整数文件。 第一个数字-后续数字的数量。 作为将此文件放入数组的最简单方法? C#

示例1:8 1 2 3 4 5 6 7 8

示例2:4 1 2 3 0

示例3:3 0 0 1

int[] numbers = File
    .ReadAllText("test.txt")
    .Split(' ')
    .Select(int.Parse)
    .Skip(1)
    .ToArray();

或者如果您每行有一个数字:

int[] numbers = File
    .ReadAllLines("test.txt")
    .Select(int.Parse)
    .Skip(1)
    .ToArray();
int[] numbers = File
    .ReadAllLines("test.txt")
    .First()
    .Split(" ")
    .Skip(1)
    .Select(int.Parse)
    .ToArray();

如果您的文件包含列样式中的所有数字(在彼此之间),那么您可以像这样读取它

static void Main()
{
    //
    // Read in a file line-by-line, and store it all in a List.
    //
    List<int> list = new List<int>();
    using (StreamReader reader = new StreamReader("file.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            list.Add(Convert.ToInt16(line)); // Add to list.
            Console.WriteLine(line); // Write to console.
        }
    }
    int[] numbers = list.toArray();
}

好的,发布后我发布了此更新,但是虽然可能有一些帮助:)

暂无
暂无

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

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