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 a single LINQ query?
CodePudding user response:
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() };