[英]Parsing data from a text file into an array
我有一個包含以下數據的平面文本文件;
Following are the names and ages in a text file.
26|Rachel
29|Chris
26|Nathan
數據保存在服務器上(例如http://domain.com/info.dat ),我想閱讀此文本文件並將其插入數組(年齡和姓名)。 我想忽略第一行(以下是....)。
我已經對代碼進行了排序,以使用 webclient 獲取數據文件,並使用 streamreader 打開 dat 文件的代碼,如下所示;
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
string[] channels = Text.Split('|');
foreach (string s in channels)
{
}
}
}
上述代碼的問題在於將其輸入到具有正確列的數組中。 誰能給我一些指示?
非常感謝
使用一些 LINQ 的答案怎么樣:
var results = from str in File.ReadAllLines(path).Skip(1)
where !String.IsNullOrEmpty(str)
let data = str.Split('|')
where data.Length == 2
select new Person { Age = Int32.Parse(data[0], NumberStyles.Integer, CultureInfo.CurrentCulture), Name = data[1] };
results
現在是IEnumerable<Person>
,您可以對其執行ToList
或ToArray
以獲取List<Person>
或Person[]
,或者您可以簡單地將結果與foreach
循環一起使用。
更新:這是使此功能更具功能所需的Person
class。
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
你可以做這樣的事情。 (沒有錯誤檢查,您可能想在解析年齡等時檢查錯誤。
class Person
{
string Name {get;set;}
int Age {get;set;}
}
List<Person> people = new List<Person>();
string line;
using (StreamReader sr = new StreamReader(path))
{
sr.ReadLine();
while ((line == sr.ReadLine()) != null)
{
string[] channels = line.Split('|');
people.Add(new Person() {Age=int.Parse(channels[0]), Name=channels[1]});
}
}
您應該使用 Dictionary 而不是 Array 來存儲數據。 示例代碼:
FileStream fs = new FileStream("filename");
Dictionary<int,string> dict = new Dictionary<int,string>();
string line = "";
fs.ReadLine(); //skip the first line
while( (line = fs.ReadLine()) != null)
{
string parts = line.split("|".ToCharArray());
dict.Add(int.Parse(parts[0]), parts[1]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.