从文件读取数据和存储的最佳方法? [英] Best way to read data and store from file?

查看:119
本文介绍了从文件读取数据和存储的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,该文件以这种方式存储数据:

I have a text file which stores data in this manner:


Player name: NAME HERE
Speed: 7
Strength: 9
Stamina: 4
Player name: ANOTHER NAME HERE
Speed: 5
Strength: 8
Stamina: 3

同一文件包含大约15个不同的球员,我想从每个球员中收集价值,存储在一个临时的比赛变量中,然后计算速度强度和耐力的平均值,并提出一个获胜者.我的第一个想法是使用正则表达式,但我目前正在研究是否还有另一种更可持续的方式来做到这一点.

The same file contains about fifteen different players, and I want to gather values from each of them, store in a temporary race variable, then calculate the mean value of the speed strength and stamina and present a winner. My first idea was to use regular expression but I am currently investigating if there are another, more sustainable way to do this.

这是我的一个附带项目,欢迎任何帮助.谢谢

This is for a side project of mine and any help is welcome. Thanks

推荐答案

定义种族类结构:

public class Race
{
    public string Name;
    public int Speed;
    public int Strength;
    public int Stamina;
}

从文本文件中读取数据,并实例化Race对象并将其收集到List<Race>中.收集完毕后,您可以从List调用Average()以获得结果.

Read your data in from your text file, and instantiate your Race objects and collect them into a List<Race>. Once collected you can call Average() from your List to get your results.

string[] myTextFileLines = File.ReadAllLines(myTextFile);

List<Race> myRaces = new List<Race>();
for (int i = 0; i < myTextFileLines.Length; i += 4)
{
    myRaces.Add(new Race()
                    {
                        Name = myTextFileLines[i].Substring(myTextFileLines[i].IndexOf(":") + 2),
                        Speed = Convert.ToInt32(myTextFileLines[i + 1].Substring(myTextFileLines[i + 1].IndexOf(":") + 2)),
                        Strength = Convert.ToInt32(myTextFileLines[i + 2].Substring(myTextFileLines[i + 2].IndexOf(":") + 2)),
                        Stamina = Convert.ToInt32(myTextFileLines[i + 3].Substring(myTextFileLines[i + 3].IndexOf(":") + 2)),
                    });
}

Console.WriteLine("Avg Speed: {0}", myRaces.Average(r => Convert.ToDouble(r.Speed)));
Console.WriteLine("Avg Strength: {0}", myRaces.Average(r => Convert.ToDouble(r.Strength)));
Console.WriteLine("Avg Stamina: {0}", myRaces.Average(r => Convert.ToDouble(r.Strength)));
Console.ReadLine();

结果(使用您在问题中提供的确切数据)

Results (using the exact data you provided in your question):

这篇关于从文件读取数据和存储的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆