Home > Blockchain >  LINQ with groupby and count, plus Name
LINQ with groupby and count, plus Name

Time:11-16

I want to display a list with owners Name and number of lists for each. The group.Key gives me the id of the person but how can i switch it for the name?

// Get all lists owned by an organization
var lists = context.SalesToolsLists.Include(x=>x.OwningUserOrganization).Where(x => uoids.Contains(x.OwningUserOrganization.Id));

// Get a dataset where each row contains OwningUserOrganization.FullName, group.Key and group.Count()
res.UOListCounts = new List<Tuple<int, int>>();
foreach (var listgroup in lists?.GroupBy(info => info.OwningUserOrganizationId).Include(x=>x)
        .Select(group => new
        {
            Metric = group.Key,
            Count = group.Count(),
          
        }).OrderBy(x => x.Metric))
{
    res.UOListCounts.Add(new Tuple<int, int>(listgroup.Metric, listgroup.Count));
}

CodePudding user response:

You just need to group items by name instead of OwningUserOrganizationId as follows:

foreach (var listgroup in lists?.GroupBy(info => info.OwningUserOrganization.FullName).Include(x=>x)
        .Select(group => new
        {
            Metric = group.Key,
            Count = group.Count(),
          
        }).OrderBy(x => x.Metric))
{
    res.UOListCounts.Add(new Tuple<int, int>(listgroup.Metric, listgroup.Count));
}

So that group.Key gives to OwningUserOrganization.FullName

And as a bonus as @gunr2171 pointed out on comments, you can move query out of the foreach and into its own variable to improve code readability.

  • Related