1

I do have an LINQ query:

var groupedResult = from address in Address.GetAddresses()
                      group new { City = address.City, HasManyInhabitants = address.Inhabitants > 20 } 
                      by address.City into addressWithInfo
                      select addressWithInfo;

That works fine. But I'm looking for the method base approach for this query. At the moment I use

var groupedResult = Address.GetAddresses()
                  .Select(a => new { City = a.City, HasManyInhabitants = a.Inhabitants > 20 })
                  .GroupBy(a => a.City)
                  .Select(a => a);

It works, but it doesn't seem to be right because the decompiled code (with ILSpy) looks not similar.

Regards, Torsten

zimmybln
  • 149
  • 3
  • 12
  • 4
    Does this answer your question? [Group by in LINQ](https://stackoverflow.com/questions/7325278/group-by-in-linq) – Yong Shun May 28 '21 at 06:56

2 Answers2

2

You just want this:

var groupedResult =
    Address
        .GetAddresses()
        .GroupBy(
            address => address.City,
            address => new
            {
                City = address.City,
                HasManyInhabitants = address.Inhabitants > 20
            });
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

into serves the purpose of assigning an identifier (i.e., variable) so you can continue querying. This is needed in the LINQ syntax because otherwise you'll not be able to access the group result.

To achieve a similar result with LINQ methods you can define a variable that takes the result returned by GroupBy() but you really don't need it to continue querying because you can chain another call to GroupBy() as you did in the example

into keyword is explained in details here https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/into