[英]How I can read numbers from text file in specific lines?
this is my text file: 这是我的文本文件:
Earnings: 17
EarningsM: 2
Level: 6
How can I set this numbers for integers? 如何设置此数字为整数?
I tried 我试过了
foreach (string line in File.ReadLines(@"C:\Program Files (x86)\makeeuro\work.txt"))
if (line.Contains("Earnings"))
button1.Text = line;
but I need only numbers, so it's now working correctly. 但是我只需要数字,所以现在可以正常使用了。 This is my integers:
这是我的整数:
int xp;
int lvlg;
int lvl;
I need to put "Earnings" value for xp, "EarningsM" for lvlg and "Level" for lvl. 我需要为xp输入“ Earnings”值,为lvlg输入“ EarningsM”,为lvl输入“ Level”。
Try this: 尝试这个:
IEnumerable<string> lines = File.ReadLines(@"C:\Program Files (x86)\makeeuro\work.txt");
Dictionary<string, int> values = lines
.Where(l => !string.IsNullOrEmpty(l))
.Select(s => s.Split(':'))
.ToDictionary(split => split[0], split => int.Parse(split[1]));
Then you'll be able to access your integer values by name like this: 然后,您将可以按如下名称访问整数值:
int xp = values["Earnings"];
and so forth. 等等。
Of course this is very crude and does no error checking, which I'll leave to you as an exercise ;-) 当然,这是非常粗糙的,并且不会进行错误检查,我将在练习中留给您;-)
A bit of explanation about the Linq operators: 关于Linq运算符的一些解释:
The Where
operator gets rid of empty lines. Where
运算符消除了空行。
The Select
operator splits each line at the :
, and projects it into an array containing two string, the key and the value. Select
运算符在:
处分割每一行,并将其投影到一个包含两个字符串,键和值的数组中。
The ToDictionary
operator creates the dictionary by selecting the first item of the split as the key, and the second as the value. ToDictionary
运算符通过选择拆分的第一项作为键,选择第二项作为值来创建字典。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.