|
1 | 1 | namespace NewLINQMethodsCsharp13
|
2 | 2 | {
|
3 |
| - public record Person(string name); |
| 3 | + record Student (string Name, string Score); |
4 | 4 | public class Program
|
5 | 5 | {
|
6 | 6 | public static void Main(string[] args)
|
7 | 7 | {
|
8 |
| - var persons = new List<Person>() { new("p1"), new("p2") }; |
| 8 | + Student[] students = [ |
| 9 | + new("Alice", "A"), |
| 10 | + new("Bob", "B"), |
| 11 | + new("Charlie", "C"), |
| 12 | + new("David", "B"), |
| 13 | + new("Eve", "A") |
| 14 | + ]; |
9 | 15 |
|
10 |
| - // Using a for loop |
11 |
| - for (int i = 0; i < persons.Count; i++) |
| 16 | + Console.WriteLine("----------Index-----------"); |
| 17 | + foreach (var (index, student) in students.Index()) |
12 | 18 | {
|
13 |
| - var person = persons[i]; |
14 |
| - Console.WriteLine($"Index: {i}, Person:{person}"); |
| 19 | + Console.WriteLine($"Student {index}: {student.Name}"); |
15 | 20 | }
|
16 | 21 |
|
17 |
| - // Using the new .NET 9 Index method. |
18 |
| - foreach ((int index, Person person) in persons.Index()) |
| 22 | + Console.WriteLine(); |
| 23 | + Console.WriteLine("----------CountBy-----------"); |
| 24 | + Console.WriteLine(); |
| 25 | + foreach (var (score, count) in students.CountBy(student => student.Score)) |
19 | 26 | {
|
20 |
| - Console.WriteLine($"Index: {index}, Person:{person}"); |
| 27 | + Console.WriteLine($"Students with a {score}-score: {count}"); |
| 28 | + } |
| 29 | + |
| 30 | + Console.WriteLine(); |
| 31 | + Console.WriteLine("----------AggregateBy-----------"); |
| 32 | + Console.WriteLine(); |
| 33 | + foreach (var (score, studentGroup) in students.AggregateBy( |
| 34 | + keySelector => keySelector.Score, |
| 35 | + seed: new List<Student>(), |
| 36 | + func: (group, student)=> [..group, student])) |
| 37 | + { |
| 38 | + Console.WriteLine($"Students with a {score}-score: {string.Join(", ", studentGroup)}"); |
21 | 39 | }
|
22 | 40 | }
|
23 | 41 | }
|
|
0 commit comments