How does Groupby work on LINQ?

Asked

Viewed 14,331 times

11

I’m having trouble understanding the operator Groupby on LINQ.

  • 1

    Do you have any specific doubt?

  • I don’t understand the syntax

  • I want an example

  • 3

    http://www.dotnetperls.com/groupby

2 answers

17


GroupBy serves to group elements according to a certain value in common between them. For example:

public class Fruta {
    public String Cor { get; set; }
    public String Nome { get; set; }
}

Suppose something like that:

var frutas = new List<Fruta>();

Suppose also that we put several fruits, with colors in common, and we want to group by colors:

var grupos = frutas.GroupBy(f => f.Cor);

grupos is an object that implements IEnumerable<IGrouping<String, Fruta>>. That is, it is a list of group elements.

An object that implements IGrouping basically has two elements in its structure:

  • Key, that is, the key value of the cluster (in our case, the name of the fruit, a String);
  • GetEnumerator, that is, the elements grouped by the key value. Here you can use the object directly, make a ToList(), use another Linq extension, etc, etc.

Notice that it looks a lot like a dictionary.

If you want to print out the names of the groups, I can do it this way:

foreach (var nomeGrupo in grupos.Select(g => g.Key)) {
    Debug.WriteLine(nomeGrupo);
}

If you want to print the fruit of each group, I can do it like this:

foreach (var listaDeFrutasPorCor in grupos) {
    Debug.WriteLine("Imprimindo frutas da cor: " + listaDeFrutasPorCor.Key);
    Debug.WriteLine("-----------------------");
    foreach (var fruta in listaDeFrutasPorCor) {
        Debug.WriteLine(fruta.Nome);    
    }
}

I made a Fiddle here.

  • 1

    Perfect Thank you !

5

As the name says, it groups data based on some criterion. It works the same or at least similar to GROUP BY of SQL.

With it you generate a data set based on another set that must have some "column" repeated. You eliminate the repetition of this data.

Taken from documentation:

using static System.Console;
using System.Collections.Generic;
using System.Linq;
 
public class Program {
    public static void Main() {
        List<Pet> pets =
            new List<Pet>{ new Pet { Name="Barley", Age=8 },
                new Pet { Name="Boots", Age=4 },
                new Pet { Name="Whiskers", Age=1 },
                new Pet { Name="Daisy", Age=4 } };
        //está agrupando por idade e depois po nome.
        //Como existe dois pets com mesma idade eles serão agrupados
        var query = pets.GroupBy(pet => pet.Age, pet => pet.Name);
        foreach (var petGroup in query) {
            WriteLine(petGroup.Key);
            foreach (var name in petGroup) WriteLine("  {0}", name);
        }
    }
}
 
class Pet {
    public string Name { get; set; }
    public int Age { get; set; }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.