© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•11mo ago•
16 replies
Faker

✅ Looping through collections with key value pairs

Hello guys, consider the following code:

// 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);
    }
}
// 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
grouping.Value
in the inner loop but here, we used
grouping
grouping
in both loops. What's happening here please, how does grouping know which one is an int or which one is the collection.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Looping through frames in a video?
C#CC# / help
2y ago
✅ Troubles with looping
C#CC# / help
14mo ago
Collections
C#CC# / help
15mo ago
Invoke method with [Optional] with default value through Reflection
C#CC# / help
2y ago