Peter Bill Peter Bill - 1 month ago 15
C# Question

How to count list items grouped by an embedded list

I have a class like

class MyClass
{
public DateTime Date { get; set; }
public List<int> IdList { get; set; }

public MyClass(DateTime initDate)
{
Date = initDate;
IdList = new List<int>();
}
}


and need to count the number of entries in a
List<MyClass>
, grouped by each
int
in
IdList
.

I have experimented with various Linq constructs, but I cannot get anything to work. Here is what I have so far:

List<MyClass> myc = new List<MyClass>();
myc.Add(new MyClass(new DateTime(2016, 1, 1)) { IdList = new List<int> { 1, 2 } });
myc.Add(new MyClass(new DateTime(2016, 1, 2)) { IdList = new List<int> { 1, 3 } });
myc.Add(new MyClass(new DateTime(2016, 1, 3)) { IdList = new List<int> { 1, 4 } });
myc.Add(new MyClass(new DateTime(2016, 1, 4)) { IdList = new List<int> { 5, 6 } });
myc.Add(new MyClass(new DateTime(2016, 1, 5)) { IdList = new List<int> { 2, 3 } });

var grouped = from p in myc
group p by p.IdList into g
select new { Id = g.Key, Count = g.Count() };
foreach (var x in grouped)
{
Console.WriteLine("ID: {0}, Count: {1}", x.Id, x.Count);
}

// Expecting output like:
// ID: 1, Count: 3
// ID: 2, Count : 2
// etc.


If there was a single
int Id
property in
MyClass
, it would be straightforward, but I cannot work out how to use the
List<int>
. Is there any alternative to writing nested loops and populating a Dictionary? Thanks for any help.

Answer

You can use SelectMany

var grouped = myc.SelectMany(x => x.IdList).GroupBy(x => x);
foreach (var i in g)
{
    Console.WriteLine(string.Format("Id: {0}, Count: {1}", i.Key,i.Count()));
}

This should give you the output you're looking for.