如何将数据从文本文件存储到数组
问题描述:
我是c#编程的新手。我需要有关如何从我的文本文件存储数据然后将其存储在数组中的帮助。
我的文本文件看起来像这样:
29/5/2015 9:10:07 AM 29
29/5/2015 9:10:07 AM 29
29/5/2015 9:10:08 AM 30
我只需要存储29,29,30等等
请帮忙..谢谢!
I am new to c# programming.. I need help on how to store the data from my text file then store it in array.
My text file looks like this:
29/5/2015 9:10:07 AM 29
29/5/2015 9:10:07 AM 29
29/5/2015 9:10:08 AM 30
I only need to store 29,29,30 and so on
please help.. thanks!
答
查看下面的示例程序。它逐行读取您的文件,然后将其拆分为单个单词(在空格上拆分),然后取最后一个单词并将其添加到列表中。如果需要,可以将此列表转换为int数组。
Check the sample program below. It reads your file line by line, then splits it into individual words (split on space) and then takes the last word and adds it into a list. You can convert this list into an int Array if you want.
class Program
{
static void Main(string[] args)
{
List<int> listOfNumbers = new List<int>();
using (StreamReader sr = new StreamReader(@"C:\Test.txt"))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (!string.IsNullOrEmpty(line))
{
listOfNumbers.Add(Convert.ToInt32(line.Split(' ').Last()));
}
}
}
}
}
//You can do this in two lines of code
//if you just want the substring after the last space
string[] lines = File.ReadAllLines(@"C:\Test.txt");
List<string> OutputLines = (from line in lines
let index = line.LastIndexOf(' ')
where index > -1 && index < line.Length - 2
select line.Substring(index + 1)).ToList();
//Or, in fluent syntax
List<string> OutputLines =
lines.Select((line) => new { text=line, index = line.LastIndexOf(' ') })
.Where(x => x.index > -1 && x.index < x.text.Length - 2)
.Select(x => x.text.Substring(x.index + 1))
.ToList();
//or, with a foreach loop
List<string> OutputLines = new List<string>();
foreach (var line in lines)
{
int index = line.LastIndexOf(' ');
if (index > -1 && index < line.Length - 2)
OutputLines.Add(line.Substring(index + 1));
}