TL ; DR:
Select can hand you each item's index. Zip walks two lists side by side.
List<string> fruits = new List<string>(new[] {"apple", "kiwi", "plum"});
List<int> prices = new List<int>(new[] {3, 1, 2});
List<string> numbered = fruits.Select((fruit, i) => (i + 1) + ". " + fruit).ToList();
// numbered holds "1. apple" and "2. kiwi" and "3. plum"
foreach (var (fruit, price) in fruits.Zip(prices)) {
Console.WriteLine(fruit + " " + price); // apple 3, kiwi 1, plum 2
}
Full lesson:
You have numbered items with a for loop and i + 1. LINQ has two shortcuts for this kind of work.
You met Select in LINQ: Where & Select. Its lambda can take a second parameter. That one is the item's index.
List<string> numbered = fruits.Select((fruit, i) => (i + 1) + ". " + fruit).ToList();
The item comes first and the index second. The index starts at 0. Add 1 for a list that people read.
a.Zip(b) walks two lists side by side. It pairs the first item of a with the first item of b. Then it pairs the second items, and so on.
Each pair is a tuple. Its parts are named First and Second. A foreach can unpack it into two names, as you did with tuples.
foreach (var (fruit, price) in fruits.Zip(prices)) {
Console.WriteLine(fruit + " costs " + price);
}
Zip can also build the new values for you. Give it a lambda with two parameters, one from each list.
List<string> tags = fruits.Zip(prices, (fruit, price) => fruit + " " + price).ToList();
Like Select, Zip gives a sequence, not a list. .ToList() turns it into a List.
The two work together. Zip first, then number the results with Select and its index.
Zip stops at the end of the shorter list. The extra items are skipped, with no error.
Your task
A quiz show keeps its players in the List players. Their points are in scores, in the same order.
First, build numbered with each player and a number from 1, like 1. Ana. Use Select with the index. The code already prints numbered.
Then loop over players.Zip(scores). Print each player with their points, like Ana has 12 points.
Expected output:
1. Ana
2. Ben
3. Cleo
Ana has 12 points
Ben has 9 points
Cleo has 15 pointsFree plan: 30 tutor messages. PRO is unlimited.
