首页 > 解决方案 > Reading from file with different line length

问题描述

does anyone know how to read from file to array(container with inheritance) when the line length is different?(I hope language barrier won't make any problems:))

 Sportas Skaitymas(Sportas sportas)
        {
            SportininkasCointainer sportininkai = new SportininkasCointainer();
            KomandaContainer komandos = new KomandaContainer();

            using (StreamReader reader = new StreamReader("Duomenys.txt"))
            {
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] values;

                    values = line.Split(';');                    
                    string a = values[0];
                    string b = values[1];
                    string c = values[2];
                    string d = values[3];
                    string e = values[4];
                    string f = values[5];
                    string g = values[6];

                    switch (values.Length)
                    {
                        case 7:
                            Krepsininkas krepsininkas = new Krepsininkas(a, b, c, int.Parse(d), int.Parse(e), int.Parse(f), int.Parse(g));
                            sportininkai.AddSportinkas(krepsininkas as Krepsininkas);
                            break;

                        case 6:
                            Futbolininkas futbolininkas = new Futbolininkas(a, b, c, int.Parse(d), int.Parse(e), int.Parse(f));
                            sportininkai.AddSportinkas(futbolininkas as Futbolininkas);
                            break;

                        case 4:
                            Komanda komanda = new Komanda(a, b, c, int.Parse(d));
                            komandos.AddKomanda(komanda);
                            break;
                    }  
                }
            return sportas;
    }

I would be very grateful :)

标签: c#

解决方案


You can use:

string a = values.Length > 0 ? values[0] : "";
string b = values.Length > 1 ? values[1] : "";

Here, string is only set when value is present else it will be ""


推荐阅读