How to get count of repeating items using group by in Linq c#

25 Apr 2014, 07:11 AM

Use the GroupBy clause and then use the Select method to get value and its counts. See the example below.

 
 List<string> strList = new List<string>()
                                       {
                                            "UK", 
                                            "USA", 
                                            "UK", 
                                            "USSR", 
                                            "USA",
                                            "DK"
                                       };

 var groupd = strList.GroupBy(x => x).Select(x => new{
                                                             Name = x.Key, 
                                                             Total = x.Count()
                                                           });
 

You can also get it using the query expression

 var grop2 = from s in strList
             group s by s into groupValue
             select new
             {
                Email = groupValue.Key,
                Total = groupValue.Count()
             };

Related Contents

15 May 2014, 08:07 AM
C#, LINQ, List
15 May 2014, 07:54 AM
C#, LINQ, List
29 Apr 2014, 03:07 AM
C#, Generic
About
Explains how to get count of repeating items using LINQ c#

Date Posted 25 Apr 2014, 06:00 AM
Author Brainy Solutions
Views 2,205
;