0

I have a database table that contains entries for every SMS customers have sent. It looks something like this:

CustomerId  SentBy  SentTo SentDate

I want to create a report that lists the total amount of sent SMS messages per customer, using LINQ (preferably fluent syntax)

var smses = smsTable.GroupBy(x => x.CustomerId);

I'm not quite sure how to loop through the result, though. I want the following output:

CustomerId  SmsCount
----------------------
1234        1756
100         333

I'd appreciate any help!

msk
  • 1,052
  • 3
  • 15
  • 31

2 Answers2

2

According to MSDN, the GroupBy returns IEnumerable<IGrouping<TKey, TElement>>and each IGrouping object contains a collection of objects of type TElement and a key.

Which means you can get the value of grouped item will be equal to the Key and each Key will associated with a collection. In your case you have to get the Key as well as the Count of items in each Group. for that the following code can be used.

var smses = smsTable.GroupBy(x => x.CustomerId)
                    .Select(y => new 
                                 { 
                                    CustomerId = y.Key,
                                    smsCount = y.Count()
                                 });
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

Try doing this:

var smses = smsTable.GroupBy(x => x.CustomerId).Select(group =>
                         new
                         {
                             CustomerId = group.Key,
                             SmsCount = group.Count()
                         });

Hope it helps!

mindOfAi
  • 4,412
  • 2
  • 16
  • 27