Loading...

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

AlexanderPetkov27 avatar AlexanderPetkov27 1 Точки

Opinion Poll не печата на конзолата

Здравейте, като използвам linq върху list  не печата нищо на конзолата. Ако махна linq-a и печата  и нз какво става ?

Като филтрирам листа с Linq  в нов лист и дебъгна виждам че нищо не се пълни в новия лист

https://pastebin.com/wRudRYJ6    Main method

https://pastebin.com/P7jiKC7n   Person класът ми е добавен с референция от друг project 

Тагове:
0
C# OOP Advanced
Elena123456 avatar Elena123456 235 Точки

Умолявам някой, ако може да погледне решението ми на тази задача- не е дълго, но се притеснявам да го пейстна в Judge, защото съм убедена, че ще гръмне. Подведох се по предишната задача и малко без да искам си усложних решението. Направих допълнителен клас People, който има лист с Person() и съответните методи-за добавяне на Person и за филтриране на хората по-големи от 30. Решението ми изглежда правилно, но не съм убедена на 100% с някои гранични случаи дали ще работи. Много моля за съвет.


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

namespace OpinionPoll
{
    class People
    {
        public People()
        {
            this.ListWithAllPeople = new List<Person>();
        }

        public void AddPerson(Person name)
        {
           this.ListWithAllPeople.Add(name);
        }
       
        public List<Person> GetOldersThanThirty()
        {
            var filterList = this.ListWithAllPeople.Where(x => x.Age > 30).ToList();
            return filterList;
        }   

        public List<Person> ListWithAllPeople {get; set;}
    }
}

 

using System;
using System.IO;
using System.Linq;

namespace OpinionPoll
{
    public static class StartUp
    {
        static void Main(string[] args)
        {
            var listWithPeople = new People();
            int number = int.Parse(Console.ReadLine());
            for (int i = 0; i < number; i++)
            {
                string[] personArray = Console.ReadLine().Split();
                string name = personArray[0];
                int age = int.Parse(personArray[1]);
                var newPerson = new Person(name, age);
                listWithPeople.AddPerson(newPerson);
            }

            var listOrderByAge = listWithPeople.GetOldersThanThirty();
            var sortFilterList = listOrderByAge.OrderBy(x => x.Name);
            foreach (var person in sortFilterList)
            {
                Console.WriteLine($"{person.Name} - {person.Age}");
            }
        }
    }
}


Има и още един клас за Person, който има Name и Age.

Ето и условието: Using the Person class, write a program that reads from the console N lines of personal information and then prints all people, whose age is more than 30 years, sorted in alphabetical order.

Input:

5

Nikolai 33

Yordan 88

Tosho 22

Lyubo 44

Stanislav 11

 

Output:

Lyubo - 44

Nikolai - 33

Yordan - 88

 

0
Axiomatik avatar Axiomatik 2422 Точки

Main:

using System;
using System.Collections.Generic;

namespace opinionPoll
{
    class Program
    {
        static void Main(string[] args)
        {
            var stats = new Statistics(new List<Person>());

            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                string[] inputSplit = Console.ReadLine()
                    .Split(" ", StringSplitOptions.RemoveEmptyEntries);
                string name = inputSplit[0];
                int age = int.Parse(inputSplit[1]);
                var person = new Person(name, age);
                stats.AddStatistics(stats.Persons, person);
            }

            stats.StatisticsPrinter(stats.Persons);
        }
    }
}

 

Statistics:

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

namespace opinionPoll
{
    public class Statistics
    {
        private List<Person> persons;

        public Statistics()
        {
            this.Persons = new List<Person>();
        }

        public Statistics(List<Person> persons)
        {
            this.Persons = persons;
        }

        public List<Person> Persons
        {
            get
            {
                return this.persons;
            }
            set
            {
                this.persons = value; 
            }
        }

        public void AddStatistics(List<Person> persons, Person person)
        {
            if (!persons.Contains(person))
            {
                persons.Add(person);
            }
        }

        public void StatisticsPrinter(List<Person> persons)
        {
            foreach (var person in persons.OrderBy(person => person.Name).Where(person => person.Age > 30))
            {
                Console.WriteLine($"{person.Name} - {person.Age}");
            }
        }
    }
}

Person:

using System;

namespace opinionPoll
{
    public class Person
    {
        private string name;

        private int age;

        public Person()
        {
        }

        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }

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

        public int Age
        {
            get
            {
                return this.age;
            }
            set
            {
                this.age = value;
            }
        }

        public override string ToString()
        {
            return $"{this.Name} - {this.Age}"; 
        }
    }
}

 

 

 

1
Elena123456 avatar Elena123456 235 Точки

@Axiomatik, 

thank you again! In fundamental module you help me so much to take in the classes.

Your class name "Statistics" is better than my class name "People" and in your method "AddStatistics" you don't add the person if list already content person. And I will add this validation in my AddPerson method.

I write properties without return and whitout declare private fields is this bad practice?

Best,

Eli

0
06/02/2021 11:06:49
Axiomatik avatar Axiomatik 2422 Точки

Setting up properties and private fields will be explained in detail in C#-Advanced and OOP. Usually properties are configured with {get; set;}, while private fields should be validated through public properties. Practise with the exercises and exams and things will start to get clearer in the process.

Best,

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