C#C
C#10mo ago
Faker

✅ Looping through collections with key value pairs

Hello guys, consider the following code:

C#
// percentileQuery is an IEnumerable<IGrouping<int, Country>>
var percentileQuery =
    from country in countries
    let percentile = (int)country.Population / 1_000
    group country by percentile into countryGroup
    where countryGroup.Key >= 20
    orderby countryGroup.Key
    select countryGroup;

// grouping is an IGrouping<int, Country>
foreach (var grouping in percentileQuery)
{
    Console.WriteLine(grouping.Key);
    foreach (var country in grouping)
    {
        Console.WriteLine(country.Name + ":" + country.Population);
    }
}

I'm a bit confused about how grouping is used in the loops. The thing is I first tried to compare it with how we loop for a dictionary but in a dictionary, we would use grouping.Value in the inner loop but here, we used grouping in both loops. What's happening here please, how does grouping know which one is an int or which one is the collection.
Was this page helpful?