LINQ: zapytania na liście obiektów i GroupBy
Kolekcje i LINQ - Podstawy C# (csharp)
LINQ najczęściej działa na listach obiektów: warunki i sortowanie odwołują się do właściwości (
s => s.Points). ThenBy dodaje drugi klucz sortowania przy remisie. GroupBy dzieli elementy na grupy o tym samym kluczu; każda grupa ma Key i jest kolekcją, więc można na niej liczyć Count() czy Average(...). Formaty {s.Name,-6} i {s.Points,3} wyrównują tekst do lewej i liczby do prawej w kolumnach.using System;
using System.Collections.Generic;
using System.Linq;
class Student
{
public string Name { get; set; }
public string Group { get; set; }
public int Points { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Name = "Ola", Group = "1A", Points = 87 },
new Student { Name = "Kuba", Group = "1B", Points = 64 },
new Student { Name = "Ewa", Group = "1A", Points = 92 },
new Student { Name = "Adam", Group = "1B", Points = 87 },
new Student { Name = "Iga", Group = "1A", Points = 55 },
};
Console.WriteLine("Ranking:");
foreach (Student s in students.OrderByDescending(s => s.Points).ThenBy(s => s.Name))
{
Console.WriteLine($"{s.Name,-6}{s.Group} {s.Points,3}");
}
Student best = students.First(s => s.Points == students.Max(x => x.Points));
Console.WriteLine($"Najlepszy wynik: {best.Name}");
foreach (var group in students.GroupBy(s => s.Group))
{
Console.WriteLine($"Klasa {group.Key}: {group.Count()} osoby, średnio {group.Average(s => s.Points):F1} pkt");
}
}
}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.