本文介绍了如何将数据从文本文件存储到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是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!
推荐答案
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));
}
这篇关于如何将数据从文本文件存储到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!