简体   繁体   English

比较和合并文本文件中的字符串数组

[英]Comparing and combining arrays of strings from text files

Right off the bat I dont think the wording of the question is accurate, I just dont really know what to write. 马上,我不认为问题的措词是正确的,我只是真的不知道该写些什么。

That being said, I have 3 txt files that I am loading into this program, Dudes, Tunes, and Bands. 话虽如此,我有3个txt文件正在加载到该程序中,它们分别是Dudes,Tunes和Bands。 Dudes is formatted like this name|instrument, Tunes like this; Dudes的格式如下:| Tunes的格式; songName|composer|band|coverArtists1|coverArtists2|etc. songName | composer | band | coverArtists1 | coverArtists2 | etc。 And band like this; 像这样的乐队 bandName|bandType|member1|member2|etc. bandName | bandType | member1 | member2 |等。 The "|" “ |” is where I split the data so each line of the text files become arrays of strings. 是我分割数据的地方,因此文本文件的每一行都变成字符串数组。

What I am trying to do now is when the user inputs the name of a band, it will return the name of the band, its type, and the list each band member and the instrument they play. 我现在要尝试的是,当用户输入乐队的名称时,它将返回乐队的名称,其类型以及每个乐队成员及其演奏乐器的列表。 This process depends on what type of band is inputted. 该过程取决于输入什么类型的频带。 For example a type RockBand needs a guitarist, drummer, bass, and vocalist. 例如,RockBand类型需要吉他手,鼓手,贝斯手和歌手。 Each type of band is its own class that is a subclass of band. 乐队的每种类型都是其自己的类,它是乐队的子类。

    class Program
    {
       static Tunes t1 = new Tunes();
       static Dudes d1 = new Dudes();
       static Bands b1 = new Bands();


        static void Main(string[] args)
        {

            do
            {

                Console.WriteLine();


            } while (DoAQuery() != "0");

        }

        static string DoAQuery()
        {
            string prompts = "0: Quit \n" +
                             "1: Who wrote <song name> \n" +
                             "2: What does <musician name> play \n" +
                             "3: What songs were written by <composer> \n" +
                             "4: Who plays in the <band name> \n" +
                             "5: Who's recorded <song name> \n" +
                             "6: What songs has the <band name> recorded \n" +
                             "7: Has the <band name> recorded <song name> \n";

            Console.WriteLine(prompts);

            Console.Write("Enter a command number: ");
            string cmd = Console.ReadLine();


            switch (cmd)
            {
                case "0" :
                    return cmd;

                case "1" :
                    Case1();
                    return cmd;

                case "2" :
                    Case2();
                    return cmd;

                case "3":
                    Case3();
                    return cmd;

                case "4":
                    Case4();
                    return cmd;

                case "5":
                    Case5();
                    return cmd;

                case "6":
                    Case6();
                    return cmd;

                case "7":
                    Case7();
                    return cmd;

                default:
                    Console.WriteLine("!!Command must be a number 0-7!!");
                    return "1";
            }


        }

        static void Case1()
        {
            Console.Write("Enter a song name: ");
            string songName = Console.ReadLine();
            t1.Case1(songName);
        }

        static void Case2()
        {
            Console.Write("Enter a musician's name: ");
            string musName = Console.ReadLine();
            d1.Case2(musName);
        }

        static void Case3()
        {
            Console.Write("Enter a composers name: ");
            string compName = Console.ReadLine();
            t1.Case3(compName);


        }

        static void Case4()
        {
            Console.Write("Enter a band name: ");
            string bandName = Console.ReadLine();
            b1.Case4(bandName);

        }

Band class 乐队班

class Band
    {
        protected Tunes t1 = new Tunes();
        protected Dudes d1 = new Dudes();

        protected string name;
        protected string type;
        protected List<Tune> recordings = new List<Tune>();

        public string Name
        {
            get { return name; }
        }

        public List<Tune> Recordings
        {
            get { return recordings; }
        }

        public string Type
        {
            get { return type; }
        }

        public Band(string[] lineAra)
        {
            name = lineAra[0];
            type = lineAra[1];
            //recordings = t1.for4(name);
        }

    }

bands class 乐队班

class Bands
    {
        private List<Band> bands = new List<Band>();
        private Dictionary<string, Band> bandsByName = new Dictionary<string, Band>();

        public Bands()
        {
            string fileName = @"C:\Users\Lkvideorang\Documents\Visual Studio 2013\Projects\KernRadio\KernRadio\bin\Debug\bands.txt";

            try
            {
                using (StreamReader myRdr = new StreamReader(fileName))
                {
                    string line;
                    while ((line = myRdr.ReadLine()) != null)
                    {
                        string[] lineAra = line.Split('|');

                        switch(lineAra[1])
                        {

                            case "RockBand":
                                {
                                    RockBand newBand = new RockBand(lineAra);
                                    bands.Add(newBand);
                                    bandsByName.Add(newBand.Name, newBand);
                                    break;
                                }
                            case "JazzCombo":
                                {
                                    JazzCombo newBand = new JazzCombo(lineAra);
                                    bands.Add(newBand);
                                    bandsByName.Add(newBand.Name, newBand);
                                    break;
                                }
                            case "SoloAct":
                                {
                                    SoloAct newBand = new SoloAct(lineAra);
                                    bands.Add(newBand);
                                    bandsByName.Add(newBand.Name, newBand);
                                    break;
                                }
                            default : 
                                {
                                     Band newBand = new Band(lineAra);
                                     bands.Add(newBand);
                                     bandsByName.Add(newBand.Name, newBand);
                                     break;
                                }

                        }
                        //Band newBand = new Band(lineAra);
                        //bands.Add(newBand);
                        //bandsByName.Add(newBand.Name, newBand);

                    }
                }
                Console.WriteLine("loaded " + bands.Count + " bands");
            }
            catch
            {
                Console.WriteLine("Error reading file! Read " + bands.Count + " tunes.");
            }
        }


        public void Case4(string bandName)
        {
            if (bandsByName.ContainsKey(bandName))
            {
                Console.WriteLine(bandsByName[bandName].Name + " is a " + bandsByName[bandName].Type);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("No band with that name found.");
            }
        }
    }

RockBand (subclass of Band) RockBand(Band的子类)

class RockBand : Band
    {


        private Musician vocalist;
        private Musician bass;
        private Musician drums;
        private Musician guitar;


        public RockBand (string[] lineAra) : base (lineAra)
        {

        //I would assign values to four members here

        }
    }

Musician Class 音乐家班

    class Musician
    {
        string name;
        string instrument;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Instrument
        {
            get { return instrument; }
            set { instrument = value; }
        }

       public Musician(string [] lineAra)
        {
            name = lineAra[0];
            instrument = lineAra[1];
        }
    }

Dudes class 杜德班

class Dudes
    {
        static List<Musician> dudes = new List<Musician>();
        Dictionary<string, Musician> dudesByName = new Dictionary<string, Musician>();

        public Dudes()
        {
            string fileName = @"C:\Users\Lkvideorang\Documents\Visual Studio 2013\Projects\KernRadio\KernRadio\bin\Debug\dudes.txt";

            try
            {
                using (StreamReader myRdr = new StreamReader(fileName))
                {
                    string line;
                    while ((line = myRdr.ReadLine()) != null)
                    {
                        string[] lineAra = line.Split('|');
                        Musician newDude = new Musician(lineAra);
                        dudes.Add(newDude);
                        dudesByName.Add(newDude.Name, newDude);

                    }
                }
                Console.WriteLine("loaded " + dudes.Count + " dudes");
            }
            catch
            {
                Console.WriteLine("Error reading file! Read " + dudes.Count + " tunes.");
            }
        }

        public void Case2(string musName)
        {

            if (dudesByName.ContainsKey(musName))
            {
                Console.WriteLine(musName + " plays " + dudesByName[musName].Instrument);
            }
            else
            {
                Console.WriteLine("No musician with that name found.");
            }
        }
    }

I know this is a lot of code for what Im pretty sure is a simple problem but I am honestly very confused and dont know where to begin with this part. 我知道这是很多代码,我很确定这是一个简单的问题,但是老实说,我很困惑,不知道从哪里开始。 Thank you in advance, Im happy to provide clarification on anything. 预先谢谢您,我很乐意提供任何澄清。

is there a reason why you want to load the files every time, rather than storing the information in a simple database ? 为什么要每次都加载文件,而不是将信息存储在简单的数据库中,是有原因的? If you stored the data in a simple database you could quickly and easily return the information with a lower overhead. 如果将数据存储在简单的数据库中,则可以以较低的开销快速轻松地返回信息。

You could even use something like entity framework which would provide objects that match the data tables. 您甚至可以使用诸如实体框架之类的东西,该实体框架将提供与数据表匹配的对象。

First of all try to give variables and methods meaningful names. 首先,尝试为变量和方法赋予有意义的名称。 Like tunesRepository instead of t1 or GetMusician instead of Case2 . tunesRepository而不是t1一样,或者像GetMusician而不是Case2

It seems like you're having trouble understanding how to manage relationships between data. 似乎您在理解如何管理数据之间的关系时遇到了麻烦。 For example, how Band can reference musicians if they're in separate files. 例如,如果乐队在单独的文件中,乐队如何引用音乐家。 A simple solution to this is to give the Bands class a reference to the Musician class. 一个简单的解决方案是为Bands类提供对Musician类的引用。 You can then lookup the musicians by name when creating the band objects: 然后,您可以在创建乐队对象时按名称查找音乐家:

public BandDatabase(MusicianDatabase musicianDatabase)
{
    this.musicianDatabase = musicianDatabase;

    string fileName = @"C:\Code\Sandbox\ConsoleApplication1\input.txt";

    string[] allLines;

    try
    {
        allLines = File.ReadAllLines(fileName);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading file! Exception: " + ex.Message);
        return;
    }

    bands = new List<Band>();

    foreach (var line in allLines)
    {
        try
        {
            string[] lineAra = line.Split('|');

            if (lineAra.Length < 2) continue;

            switch (lineAra[1])
            {
                case "RockBand":
                    bands.Add(CreateRockBand(lineAra));
                    break;
                // Rest of cases
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error parsing line {0}. Exception: {1}", line, ex.Message);
        }
    }

    bandsByName = bands.ToList().ToDictionary(x => x.Name, x => x);

    Console.WriteLine("loaded " + bands.Count + " bands");
}

private RockBand CreateRockBand(string[] lineAra)
{
    Musician vocalist = null;
    Musician bass = null;
    Musician drums = null;
    Musician guitar = null;

    if (lineAra.Length >= 3) 
        vocalist = musicianDatabase.GetMusicianByName(lineAra[2]);

    if (lineAra.Length >= 4)
        bass = musicianDatabase.GetMusicianByName(lineAra[3]);

    if (lineAra.Length >= 5)
        drums = musicianDatabase.GetMusicianByName(lineAra[4]);

    if (lineAra.Length >= 6)
        guitar = musicianDatabase.GetMusicianByName(lineAra[5]);

    return new RockBand(lineAra, vocalist, bass, drums, guitar);
}

You'll need to update the Band class a bit for the above constructor to work: 您需要稍微更新Band类,以使上面的构造函数起作用:

public class RockBand : Band
{
    public RockBand(string[] lineAra, Musician vocalist, Musician bass, Musician drums, Musician guitar)
        : base(lineAra)
    {
        Vocalist = vocalist;
        BassPlayer = bass;
        Drummer = drums;
        GuitarPlayer = guitar;
    }

    public Musician Vocalist { get; set; }

    private Musician BassPlayer { get; set; }

    private Musician Drummer { get; set; }

    private Musician GuitarPlayer { get; set; }
}

Then you would need to initialize in your Main method like so: 然后,您将需要在Main方法中进行初始化,如下所示:

private static MusicianDatabase musicianDatabase;
private static BandDatabase bandDatabase;

static void Main(string[] args)
{
    musicianDatabase = new MusicianDatabase();
    bandDatabase = new BandDatabase(musicianDatabase);
}

And you can then print the details when requested: 然后您可以根据要求打印详细信息:

static void PrintBandDetails()
{
    Console.Write("Enter a band name: ");
    string bandName = Console.ReadLine();

    var band = bandDatabase.GetBand(bandName);

    if (band == null)
    {
        Console.WriteLine("Invalid band name")
        return;
    }

    Console.WriteLine("Guitarist was " + band.GuitarPlayer);
    // etc.

    var tunes = tuneDatabase.GetByBand(bandName);

    Console.WriteLine("Tunes:");

    foreach(var t in tunes)
        Console.WriteLine(t);
}

I hope this makes a bit more sense. 我希望这更有意义。 I've tried to structure everything in terms that you should understand. 我试图用您应该理解的术语来构建所有内容。 But if there's still parts that are confusing you let me know. 但是,如果仍有部分令人困惑,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM