简体   繁体   中英

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:

{
   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?

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 totals = group.Count();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM