SETI
64 / 49 / 18
Регистрация: 09.04.2018
Сообщений: 210
1

Из List<Person> в .txt

25.04.2018, 09:04. Показов 2200. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте!
У меня есть List<Person>, надо записать его элементы в текстовый файл.
C#
1
2
3
4
5
6
7
8
9
10
11
List<Person> person = new List<Person>(5);
            person.Add(new Developer("Karl", 32000, "junior"));
            person.Add(new Teacher("John", 25000, "Math"));
            person.Add(new Teacher("Lera", 27000, "History"));
            person.Add(new Developer("Arthr", 37000, "senior"));
            person.Add(new Developer("Sergiy", 35000, "middle"));
using (StreamWriter sw = new StreamWriter("D:/ClassProject.txt"))
            {
                foreach (var k in person)
                    sw.WriteLine(k);
            }
Если реализовать данный код то выводит не значение,а это
Из List<Person> в .txt

Полная версия кода:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace ConsoleApp12
{
    class Program
    {
        static void Main()
        {
            List<Person> person = new List<Person>(5);
            person.Add(new Developer("Karl", 32000, "junior"));
            person.Add(new Teacher("John", 25000, "Math"));
            person.Add(new Teacher("Lera", 27000, "History"));
            person.Add(new Developer("Arthr", 37000, "senior"));
            person.Add(new Developer("Sergiy", 35000, "middle"));
            foreach (var el in person)
            {
                el.Print();
            }
            Console.WriteLine("Enter a name please?");
            string NeedName;
            NeedName = Console.ReadLine();
            foreach(var el in person)
            {
                if(NeedName == el.Name)
                {
                    el.Print();
                }
            }
            person.Sort();
            Console.WriteLine();
            foreach (var el in person)
            {
                el.Print();
            }
            Console.WriteLine();
            using (StreamWriter sw = new StreamWriter("D:/ClassProject.txt"))
            {
                foreach (var k in person)
                    sw.WriteLine(k);
            }
            Console.WriteLine();
                Console.WriteLine("Staff is: ");
            List<Staff> staff = new List<Staff>();
            foreach(var el in person)
            {
                if (el is Staff)
                    staff.Add((Staff)el);
            }
            foreach (var el in staff)
                el.Print();
            staff.Sort();
            Console.WriteLine();
            foreach (var el in staff)
                el.Print();
            Console.WriteLine();
            Console.ReadLine();
        }
       
    }
    class Person:IComparable<Person>
    {
         public int CompareTo(Person other)
        {
            return Name.CompareTo(other.Name);     
        }
        private string name;
        public Person(string name)
        {
            this.name = name;
        }
        virtual public string Name
        {
            get
            {
                return name;
            }
        }
        virtual public void Print()
        {
            Console.WriteLine("Name : {0}", this.name);
        }
    }
    class Staff : Person,IComparable<Staff>
    {
        public int CompareTo(Staff other)
        {
            return salary.CompareTo(other.salary);
        }
        protected int salary;
        public Staff(string name, int salary) : base(name)
        {
            this.salary = salary;
        }
        override public string Name
        {
            get
            {
                return base.Name ;
            }
        }
        public override void Print()
        {
            Console.WriteLine("Person {0} has salary {1}", Name, this.salary);
        }
    }
    class Teacher : Staff
    {
        private string subject;
        public Teacher(string name, int salary, string subject) : base(name, salary)
        {
            this.subject = subject;
        }
        public override void Print()
        {
            Console.WriteLine("{0} , teacher of {1} has salary {2}", Name, subject, salary);
        }
    }
    class Developer : Staff
    {
        private string level;
        public Developer(string name, int salary, string level) : base(name, salary)
        {
            this.level = level;
        }
        public override void Print()
        {
            Console.WriteLine("{0}, with level {1} has salary {2}", Name, level, salary);
        }
    }
}
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
25.04.2018, 09:04
Ответы с готовыми решениями:

List<Person> и AddRange
Как изменить следующий код, чтобы заработал ?.. using System; using System.Collections.Generic;...

Сортировка в List<Person> по фамилии и году рождения
Здравствуйте форумчане. У меня возникла проблема при сортировке в List. Я делаю стандартное...

Сохранение данных из List<string> в txt
многопоточный парсер html. данные парсятся регулярными выражениями и заносятся в List &lt;string&gt;....

Работа с List<> и базой данных в txt
Всем привет! Я считал строки с файла вот такой строчкой кода: List&lt;string&gt; database =...

6
Эксперт .NET
6316 / 3935 / 1577
Регистрация: 09.05.2015
Сообщений: 9,237
25.04.2018, 09:06 2
Нужно в вашем классе переопределить метод ToString().
0
SETI
64 / 49 / 18
Регистрация: 09.04.2018
Сообщений: 210
25.04.2018, 09:07  [ТС] 3
Someone007, Пробовал, но не получилось, возможно код пишу не правильно. Можете написать?
0
Эксперт .NET
6316 / 3935 / 1577
Регистрация: 09.05.2015
Сообщений: 9,237
25.04.2018, 09:09 4
Лучший ответ Сообщение было отмечено orestsyn как решение

Решение

Как-то так
C#
1
2
3
4
public override string ToString()
{
    return string.Format("Name : {0}", this.name);
}
аналогично для других классов
1
SETI
64 / 49 / 18
Регистрация: 09.04.2018
Сообщений: 210
25.04.2018, 09:12  [ТС] 5
Someone007, Программа не видит name.
0
Эксперт .NET
6316 / 3935 / 1577
Регистрация: 09.05.2015
Сообщений: 9,237
25.04.2018, 09:13 6
Цитата Сообщение от orestsyn Посмотреть сообщение
Программа не видит name.
Не туда добавляете метод.
0
SETI
64 / 49 / 18
Регистрация: 09.04.2018
Сообщений: 210
25.04.2018, 09:24  [ТС] 7
Someone007, Добавил формат.вывод как вы и говорили.
Из List<Person> в .txt

Спасибо большое.Все работает.
Финальная версия кода:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace ConsoleApp12
{
    class Program
    {
        static void Main()
        {
            List<Person> person = new List<Person>(5);
            person.Add(new Developer("Karl", 32000, "junior"));
            person.Add(new Teacher("John", 25000, "Math"));
            person.Add(new Teacher("Lera", 27000, "History"));
            person.Add(new Developer("Arthr", 37000, "senior"));
            person.Add(new Developer("Sergiy", 35000, "middle"));
            foreach (var el in person)
            {
                el.Print();
            }
            Console.WriteLine("Enter a name please?");
            string NeedName;
            NeedName = Console.ReadLine();
            foreach(var el in person)
            {
                if(NeedName == el.Name)
                {
                    el.Print();
                }
            }
            person.Sort();
            Console.WriteLine();
            foreach (var el in person)
            {
                el.Print();
            }
            Console.WriteLine();
            using (StreamWriter sw = new StreamWriter("D:/ClassProject.txt"))
            {
                foreach (var k in person)
                    sw.WriteLine(k);
            }
            Console.WriteLine();
                Console.WriteLine("Staff is: ");
            List<Staff> staff = new List<Staff>();
            foreach(var el in person)
            {
                if (el is Staff)
                    staff.Add((Staff)el);
            }
            foreach (var el in staff)
                el.Print();
            staff.Sort();
            Console.WriteLine();
            foreach (var el in staff)   
                el.Print();
            Console.WriteLine();
            Console.ReadLine();
        }
       
 
    }
    class Person:IComparable<Person>
    {
         public int CompareTo(Person other)
        {
            return Name.CompareTo(other.Name);     
        }
        private string name;
        public Person(string name)
        {
            this.name = name;
        }
        virtual public string Name
        {
            get
            {
                return name;
            }
        }
        virtual public void Print()
        {
            Console.WriteLine("Name : {0}", this.name);
        }
       
    }
    class Staff : Person,IComparable<Staff>
    {
        public int CompareTo(Staff other)
        {
            return salary.CompareTo(other.salary);
        }
        protected int salary;
        public Staff(string name, int salary) : base(name)
        {
            this.salary = salary;
        }
        override public string Name
        {
            get
            {
                return base.Name ;
            }
        }
        public override void Print()
        {
            Console.WriteLine("Person {0} has salary {1}", Name, this.salary);
        }
        public override string ToString()
        {
            return String.Format("Salary is {0}",salary);
        }
    }
    class Teacher : Staff
    {
        private string subject;
        public Teacher(string name, int salary, string subject) : base(name, salary)
        {
            this.subject = subject;
        }
        public override void Print()
        {
            Console.WriteLine("{0} , teacher of {1} has salary {2}", Name, subject, salary);
        }
        public override string ToString()
        {
            return String.Format("{0},with subject {1} has salary {2}", this.Name, subject, salary);
        }
    }
    class Developer : Staff
    {
        private string level;
        public Developer(string name, int salary, string level) : base(name, salary)
        {
            this.level = level;
        }
        public override void Print()
        {
            Console.WriteLine("{0}, with level {1} has salary {2}", Name, level, salary);
        }
        public override string ToString()
        {
            return String.Format("{0},with level {1} has salary {2}",this.Name,level,salary);
        }
    }
}
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.04.2018, 09:24
Помогаю со студенческими работами здесь

Заполнить массив List строками из txt файла
Дан файл в котором 10 строк (имена) нужно добавить эти строки в массив List, вот код который это...

Vector, push_back. Cannot convert parameter 1 from 'person' to 'person ^'
Помогите разобраться с push_back. Появляется ошибка error C2664: 'void std::vector&lt;_Ty&gt;::...

Создайте класс person. Создайте тип people, описывающий массив элементов типа person.
Создайте класс person. У него должны быть поля: name: string; sex: (&quot;муж&quot;, &quot;жен&quot;); height:...

Запись в файл txt построчно из <list>
# include &lt;iostream&gt; # include &lt;list&gt; # include &lt;string&gt; # include &lt;fstream&gt; # include &lt;cstdio&gt;...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru