Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Value and Count of that value using LINQ or lambda expression

Tags:

c#

.net

lambda

linq

A list of data object in the below format

Col1  Col2  Col3

B     45    36    
B     12    69   
A     46    76    
C     89    09    
B     451   37   
D     435   46   
A     450   50   
D     98    43   
B     358   39
A     987   89

Need to get result set like following format ( 'A' occurred 3 times ,'B' occurred 4 times etc.)

Value  Count

A      3   
B      4  
C      1    
D      2

How to get result set like above using LINQ or lambda expressions?

like image 816
User_MVC Avatar asked Oct 24 '12 05:10

User_MVC


2 Answers

You can achieve it by lambda expression like

var list = from x in dataObjects
           group x by x.Col1 into g
           select new { Value = g.Key, Count = g.Count() };

And By using Linq Extension method GroupBy as answered by @Asif

like image 170
Yograj Gupta Avatar answered Sep 24 '22 11:09

Yograj Gupta


You can use GroupBy for that.

var groupedlist = list.GroupBy(c => c.Col1)
                      .Select((key, c) => new {Value = key, Count = c.Count()});
like image 32
Asif Mushtaq Avatar answered Sep 22 '22 11:09

Asif Mushtaq