TIANLUN ZHU
TIANLUN ZHU

Reputation: 351

What will GroupBy in LINQ do if it has two parameters?

I am trying to understand the code below:

Color32[] colors = mesh.colors32;
IEnumerable<IGrouping<byte, int>> hierarchyMap = colors.Select((color, index) => new { color, index }).GroupBy(c => c.color.g, c => c.index);

I used google and only found some tutorials for GroupBy(xxx)(only one parameter inside brackets), which means xxx is the key for the group. What if there were two parameters inside the brackets?

Upvotes: 1

Views: 919

Answers (2)

Anu Viswan
Anu Viswan

Reputation: 18153

Update

When using two parameters in the GroupBy method, the two parameters represents,

keySelector Func<TSource,TKey>

A function to extract the key for each element.

elementSelector Func<TSource,TElement>

A function to map each source element to an element in the IGrouping.

What it does it is that it groups the sequence based on the first parameters, and projects each element of the group using the function specificied as second parameter.

Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

Grouping with Two Keys

If your intension is to group by two keys, then could use an anonymous type for grouping by multiple keys

.GroupBy(c => new {c.color.g, c.index})

For example, from the code in OP

 colors.Select((color, index) => new { color, index })
       .GroupBy(c => new {c.color.g, c.index});

Upvotes: 3

Oshi
Oshi

Reputation: 504

Technically, the accepted answer is trying to group by using two keys. It doesn't explain what if there are two parameters inside the GroupBy bracket.

If there are two parameters inside the bracket, it will group the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

Let say we have an Employee class

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}

And then the code logic is below.

var employees = new List<Employee>
{ 
    new Employee { Name="Dave", Age=25 },
    new Employee { Name="John", Age=23 },
    new Employee { Name="Michael", Age=30 },
    new Employee { Name="Bobby", Age=30 }, 
    new Employee { Name="Tom", Age=25 }, 
    new Employee { Name="Jane", Age=21 }
};

var query = employees.GroupBy(employee => employee.Age, employee => employee.Name);

foreach (IGrouping<int, string> employeeGroup in query)
{
    Console.WriteLine(employeeGroup.Key);
    foreach (string name in employeeGroup)
    {
        Console.WriteLine($"=> {name}");
    }
}

The output will be:

25
=> Dave
=> Tom
23
=> John
30
=> Michael
=> Bobby
21
=> Jane

Reference from MSDN

Upvotes: 5

Related Questions