S
S
Stazhor2019-01-21 17:17:35
.NET
Stazhor, 2019-01-21 17:17:35

Why doesn't it add an element to the list?

The task is to add user data to the class fields, and then the class object itself to the list.

public List<Meetings> meet = new List<Meetings>();

        public void CreateMeet()
        {
            Console.WriteLine("Введите дату встречи:");
            string dateMeeting = Console.ReadLine();
            Console.WriteLine("Введите время начала встречи:");
            string startMeeting = Console.ReadLine();
            Console.WriteLine("Введите время конца встречи:");
            string endMeeting = Console.ReadLine();

            meet.Add(new Meetings { DateMeeting = dateMeeting, StartMeeting = startMeeting, EndMeeting = endMeeting});

            Console.WriteLine("Встреча добавлена! \n");

But when viewing the content through another method, it doesn't output anything.
public void ShowMeetings()
        {
            foreach (Meetings meet in meet)
            {
                Console.WriteLine($"Дата встречи: {meet.DateMeeting}, Начало встречи: {meet.StartMeeting}, Конец встречи: {meet.EndMeeting}");
            }
            Console.WriteLine();
         }

And here is the question: Am I doing something wrong at the stage of adding an instance of the Meetings class to the list, or when I display it through foreach? I tried to add a class object to the list at the code level, it is added and displayed successfully. Here is the code:
meet.Add(new Meetings { DateMeeting = "2019-01-21", StartMeeting = "12:31", EndMeeting = "12:32" });
            foreach (Meetings meet in meet)
            {
                Console.WriteLine($"Дата встречи: {meet.DateMeeting}, Начало встречи: {meet.StartMeeting}, Конец встречи: {meet.EndMeeting}");
            }

Help me to understand)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Foggy Finder, 2019-01-22
@Stazhor

As already correctly pointed out, the problem is that you are creating a new ManagerMeeting instance each time :

public void Route(string answer)
{
    var manager = new ManagerMeeting();

I will also leave a few comments about the code:
1. You are using inheritance incorrectly.
2. If there is no additional check for the correctness of field values ​​in property setters, then it is better to use auto-properties.
3. Too complex structure - Menu , Route classes seem redundant. For such simple scenarios, it is easier to move the methods of the listed classes to Program .
4. The ManagerMeeting class is too strongly connected to the console, in addition, there is a dependency on Menu . If you want to provide methods for managing a collection (a list of meetings), then expose the necessary methods and already work with them.
5. For formatted output of your own classes, it is convenient to override the .ToString()
method Slightly rewritten classes, taking into account the above:
class Meetings // Класс встреч
    {
        public string DateMeeting { get; set; }
        public string StartMeeting { get; set; }
        public string EndMeeting { get; set; }

        public override string ToString()
        {
            return $"Дата встречи: {DateMeeting}, Начало встречи: {StartMeeting}, Конец встречи: {EndMeeting}";
        }
    }

    class ManagerMeeting //  Класс управление встречами
    {
        public List<Meetings> MeetingList { get; } = new List<Meetings>();
        public void Add(Meetings meet)
        {
            MeetingList.Add(meet);
        }
        public string FormatMeetings()
        {
            StringWriter sw = new StringWriter();
            foreach (var meet in MeetingList)
                sw.WriteLine(meet);
            return sw.ToString();
        }  
    }

menu:
class Program
    {
        static ManagerMeeting manager = new ManagerMeeting();
        public static void ShowMainMenu()
        {
            Console.WriteLine("Выберите действие: \n1. Показать все встречи\n2. Создать новую встречу");
        }

        public static bool Handler()
        {
            Console.Clear();
            ShowMainMenu();
            string answer = Console.ReadLine();
            switch (answer)
            {
                case "1":
                    var result = manager.FormatMeetings();
                    if (string.IsNullOrWhiteSpace(result))
                        Console.WriteLine("Список пуск");
                    else
                        Console.WriteLine(manager.FormatMeetings());
                    return true;
                case "2":
                    manager.Add(ReadMeeting());
                    return true;
                default:
                    return false;
            }
        }

        public static void Main(string[] args)
        {
            while (Handler()) Console.ReadKey(true);
            Console.ReadKey(true);
        }

        public static Meetings ReadMeeting()
        {
            Console.WriteLine("Введите дату встречи:");
            var date = Console.ReadLine();
            Console.WriteLine("Введите время начала встречи:");
            var startMeeting = Console.ReadLine();
            Console.WriteLine("Введите время конца встречи:");
            var endMeeting = Console.ReadLine();

            Console.WriteLine("Встреча добавлена! \n ");
            //Для проверки, записываются ли поля - записываются
            Console.WriteLine(date + startMeeting + endMeeting);
            return new Meetings
            {
                DateMeeting = date,
                StartMeeting = startMeeting,
                EndMeeting = endMeeting
            };
        }
    }

Of course, the code above is also far from ideal (there is always something to improve). For example:
Consider data validation:
In reading information from the console:
* use data types that are best suited for describing properties ( DateTime for date and time instead of the generic string )
* write helper methods GetInteger , GetDateTime and others that will return the result only after as the user entered the correct data.
In the ManagerMeeting class :
* Let the Add method return bool instead of voiddepending on the success of the addition (for example, to provide scenarios for adding a long-past meeting).
Etc.

A
Alexey Pavlov, 2019-01-21
@lexxpavlov

You are probably recreating the meet list somewhere. Put readonly on the meet field (better yet, rename it to MeetingsList)
This will prevent accidental overwriting of the variable.
>foreach (Meetings meet in meet)
There is an error in the code, you cannot create a loop counter variable Meetings meet, because there is already a variable named meet. If an error does not occur here, then, most likely, in one of the two names, instead of the English "e", there is a Russian "e".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question