Skip to content

Commit 2a5e7c5

Browse files
committed
NewLINQMethodsCsharp13 (Index, CountBy, AggregateBy)
1 parent 064dae9 commit 2a5e7c5

File tree

1 file changed

+27
-9
lines changed

1 file changed

+27
-9
lines changed

NewLINQMethodsCsharp13/Program.cs

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,41 @@
11
namespace NewLINQMethodsCsharp13
22
{
3-
public record Person(string name);
3+
record Student (string Name, string Score);
44
public class Program
55
{
66
public static void Main(string[] args)
77
{
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+
];
915

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())
1218
{
13-
var person = persons[i];
14-
Console.WriteLine($"Index: {i}, Person:{person}");
19+
Console.WriteLine($"Student {index}: {student.Name}");
1520
}
1621

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))
1926
{
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)}");
2139
}
2240
}
2341
}

0 commit comments

Comments
 (0)