2010-04-28 70 views
1

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

实施例1:8 1 2 3 4 5 6 7 8

实施例2:4 1 2 3 0

实施例3:3 0 0 1

+1

请编辑你的问题如何文本文件看起来像,逗号分隔,换行符分开,制表符分隔... – Snake 2010-04-28 07:42:41

+0

我有类似的问题,如果有帮助:http://stackoverflow.com/questions/2290254/read-text-data- from-file-using-linq – 2010-04-28 07:42:54

+1

这些数字是以二进制形式存储还是它是一个文本文件,每行可以被解释为一个整数? – 2010-04-28 07:42:59

回答

8
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(); 
+0

太棒了。 – Snake 2010-04-28 07:46:21

+0

这还包括数组中每行数量的“数量”。 – 2010-04-28 07:50:56

+0

@Rob,好评,更新了我的答案。 – 2010-04-28 07:53:51

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

:每行有一个数包括在列样式的所有数字(下海誓山盟),比你能喜欢这个

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

OK,后读它,我公布这之后进行了更新,但可能有一定的帮助虽然:)

+0

非常感谢你! – Alexry 2010-04-28 07:52:10

相关问题