Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group By, Count and get Total by itens inside list

I have an Account object like:

public class Account
{
   public int Id { get; set; }
   public List<Elegibilities> Elegibilities { get; set; }
}

public class Elegibilities
{
   public int Id { get; set; }
   public string Label { get; set; }
   public bool Value { get; set;}
}

My repository returns a List of Account. List<Account>

I want to group by and count by items in Elegibilities and the output would be like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
   Total: 30,
    [
       {
          Id : 1,
          Label: "Elegibility1",
          Count: 10
       },
       {
          Id : 2,
          Label: "Elegibility2",
          Count: 20
       }
    ]
}

I’m having issues because it’s a list inside another list.

Is it possible to solve in single linq query?

>Solution :

Look’s like you don’t want any data related to the Accounts,

This gives you a simple flat list to work with.

var flatList = accounts.SelectMany(a => a.Elegibilities);

This could be another example if you needed to include accounts related data to the output.

var group = from a in accounts
            from el in a.Elegibilities
            group el by el.Id into elGroup
            select new
            {
                Id = elGroup.Key,
                Count = elGroup.Count(),
                Label = elGroup.First().Label
            };

In the end you can access your group totals.

var result = new { Totals = group.Count() , Elegibilities = group.ToList() };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading