Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Elena123456 avatar Elena123456 235 Точки

6. Students 2.0- ProgrammingFundamentals

Здравейте, може ли помощ за логиката ми за следната задача, тъй като за OOP в Fundamentala се отделя само една лекция, в която не се решават и всички задачи от Лаба. Лекторите дават всичко от себе си, но просто материала е много голямо количество за да бъде поместен в една лекция от 3 часа. Търсих и информация в stack overflow за реализиране на моята логика за конкретната задача, но възможностите ми дадоха резултат 0/100 за жалост.

Ето и задачата: https://judge.softuni.bg/Contests/Practice/Index/1214#5

Use the class from the previous problem. If you receive a student, which already exists (first name and last name
should be unique) overwrite the information.

Input

John Smith 15 Sofia
Peter Ivanov 14 Plovdiv
Peter Ivanov 25 Plovdiv
Linda Bridge 16 Sofia
Linda Bridge 27 Sofia
Simon Stone 12 Varna

end

Sofia

Output

John Smith is 15 years old.
Linda Bridge is 27 years old.

 

Логиката ми:

1. Ще чета стринговете: firstName, lastName, age, city в while цикъл, докaто командата е различна от "end".

2. Ако съществува в ListOfStudents обекта student.firstName==firstName(стринга) и същевременно student.lastName==lastName(стринга), то значи ще имаме опит за презаписване на информация.

3. Намирам кой е този индекс в ListOfStudents и го изтривам, като оставям да се презапише новата информация, т.е. създавам нов обект student и го добавям към ListOfStudents.

4.Ако нямаме опит за презаписване, то винаги ще си създавам нов обект student и ще го добавям към листа.

5. Чета от конзолата нов град и спрямо този град ще филтрирам ListOfStudents и ще печатам само елементите от новия List-  FilteredStudent.

 

 

using System;
using System.Linq;
using System.Collections.Generic;


namespace ObjectsAndClasses
{
    class MainClass
    {
        public static void Main()
        {
            var listOfStudents = new List<Student>();

            string command = Console.ReadLine();
            while (command != "end")
            {
                string[] commandArrguments = command.Split();
                string firstName = commandArrguments[0];
                string lastName = commandArrguments[1];
                string agee = commandArrguments[2];
                string city = commandArrguments[3];
                Student student = null;


                bool fistNameExist = listOfStudents.Exists(s => s.FirstName.Contains(firstName));
                bool lastNameExist = listOfStudents.Exists(s => s.LastName.Contains(lastName));
                if (fistNameExist && lastNameExist)
                {
                    var firstRepitableIndex = listOfStudents.IndexOf(student);
                    listOfStudents.RemoveAt(firstRepitableIndex);
                }

                student = new Student();
                student.FirstName = firstName;
                student.LastName = lastName;
                student.Agee = agee;
                student.City = city;
                listOfStudents.Add(student);


                command = Console.ReadLine();
            }

            string filteredCity = Console.ReadLine();
            List<Student> FilteredStudent = listOfStudents.Where(s => s.City == filteredCity).ToList();
            foreach (var student in FilteredStudent)
            {
                Console.WriteLine($"{student.FirstName} {student.LastName} is {student.Agee} years olg.");
            }
        }
    }

    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Agee { get; set; }
        public string City { get; set; }

    }
}

0
Fundamentals Module 10/08/2020 22:46:59
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

Hi,

It's normal that at the beginning classes and objects are difficult to work with, the only solution is to practice with exercises and to watch lectures from C#-Advanced were more explanations are given.

Line 23,24 : Use Linq command to gain access to an individual object in your listOfStudents. If the student exists (meaning is not null) then you can set his/her new name in the else validation Line 37-44. Without the else validation the details of the student will always be changed, which should not happen when the student is being created for the first time.

Refactored code(100%):

using System;
using System.Linq;
using System.Collections.Generic;


namespace ObjectsAndClasses
{
    class MainClass
    {
        public static void Main()
        {
            var listOfStudents = new List<Student>();

            string command = Console.ReadLine();
            while (command != "end")
            {
                string[] commandArrguments = command.Split();
                string firstName = commandArrguments[0];
                string lastName = commandArrguments[1];
                string age = commandArrguments[2];
                string city = commandArrguments[3];

                Student student = listOfStudents
                    .FirstOrDefault(s => s.FirstName == firstName && s.LastName == lastName);

                //bool fistNameExist = listOfStudents.Exists(s => s.FirstName.Contains(firstName));
                //bool lastNameExist = listOfStudents.Exists(s => s.LastName.Contains(lastName));
                if (student != null)
                {
                    //var firstRepitableIndex = listOfStudents.IndexOf(student);
                    //listOfStudents.RemoveAt(firstRepitableIndex);
                    student.FirstName = firstName;
                    student.LastName = lastName;
                    student.Agee = age;
                    student.City = city;
                }
                else
                {
                    student = new Student();
                    student.FirstName = firstName;
                    student.LastName = lastName;
                    student.Agee = age;
                    student.City = city;
                    listOfStudents.Add(student);
                }

                command = Console.ReadLine();
            }

            string filteredCity = Console.ReadLine();
            List<Student> FilteredStudent = listOfStudents.Where(s => s.City == filteredCity).ToList();
            foreach (var student in FilteredStudent)
            {
                Console.WriteLine($"{student.FirstName} {student.LastName} is {student.Agee} years old.");
            }
        }
    }

    public class Student
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Agee { get; set; }

        public string City { get; set; }
    }
}
 

2
Elena123456 avatar Elena123456 235 Точки

Hello Axiomatik,

I really appreciate you helping me out ! Thanks to you, now I know how I can set individual objects in same list without necessary removing another and adding the same.

All the best!

Elena

0
11/08/2020 12:24:39
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.