Как из экземпляров класса взять уникальные значения
Дан класс Lesson, представляющий урок:
public class Lesson
{
public string Name { get; set; }
public Lesson(string name)
{
Name = name;
}
}
Также есть класс Student. У данного класса одно из свойств – это список всех уроков, которые он посещает:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public List<Lesson> Lessons { get; set; }
public Student(int age, string name, List<Lesson> lessons)
{
Age = age;
Name = name;
Lessons = lessons;
}
}
Нужно реализовать метод GetUniqueLessonsCount, который принимает коллекцию студентов studens. Метод должен найти все уроки студентов старше 20 лет. А затем вернуть количество уникальных уроков.
Код для проверки:
static void Main()
{
var students = new List<Student>
{
new Student(26, "Mark", new List<Lesson>
{
new Lesson("C# для продвинутых"),
new Lesson("Linq2")
}),
new Student(20, "Alexey", new List<Lesson>
{
new Lesson("C++"),
new Lesson("JavaScript")
}),
new Student(18, "Natasha", new List<Lesson>
{
new Lesson("SQL"),
new Lesson("Python")
}),
new Student(19, "Elena", new List<Lesson>
{
new Lesson("C++"),
new Lesson("PHP")
}),
new Student(21, "Joseph", new List<Lesson>
{
new Lesson("C# для продвинутых"),
new Lesson("Linq"),
new Lesson("Python"),
})
};
var uniqueLessonsCount = GetUniqueLessonsCount(students);
Console.WriteLine(uniqueLessonsCount);
}
Код выводит: 4
Я написал такой метод
static int GetUniqueLessonsCount(IEnumerable<Student> students)
{
var b = students.Where(x => x.Age > 20).SelectMany(x => x.Lessons).Select(x => x.ToString());
return b;
}
Вытащил уроки, но не понимаю как из этих уроков вытащить уникальные уроки. Когда использую Distinct
var b = students.Where(x => x.Age > 20).SelectMany(x => x.Lessons).Distinct().Select(x=> x).Distinct().Count();
Выводит 5 - Должно быть 4 Что я делаю не так?
Ответы (2 шт):
Автор решения: Дима Рейхц
→ Ссылка
Надо было просто сравнивать по имени курса и не парится, почему-то в голову не пришло.
static int GetUniqueLessonsCount(IEnumerable<Student> students)
{
var b = students.Where(x => x.Age > 20).SelectMany(x => x.Lessons);
var d = b.Select(x => x.Name).Distinct().Count();
return d;
}
Автор решения: Дима Рейхц
→ Ссылка
static int GetUniqueLessonsCount(IEnumerable<Student> students)
{
var lessons = students.Where(student => student.Age > 20).SelectMany(student => student.Lessons);
var uniqueLessons = lessons.Distinct(new LessonIEqualityComparer());
return uniqueLessons.Count();
}
class LessonIEqualityComparer : IEqualityComparer<Lesson>
{
public bool Equals(Lesson x, Lesson y)
{
return x.Name == y.Name;
}
public int GetHashCode(Lesson obj)
{
return obj.Name.GetHashCode();
}
}