User_MVC
User_MVC

Reputation: 261

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

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?

Upvotes: 6

Views: 4654

Answers (5)

Mazhar Khan
Mazhar Khan

Reputation: 404

List<TestOverFlow> list = new List<TestOverFlow>() 
{
  new TestOverFlow {Col1="B",Col2=45,Col3=36},
  new TestOverFlow {Col1="B",Col2=12,Col3=69},
  new TestOverFlow {Col1="A",Col2=46,Col3=76},

  new TestOverFlow {Col1="C",Col2=89,Col3=09},
  new TestOverFlow {Col1="C",Col2=10,Col3=09},
  new TestOverFlow {Col1="C",Col2=89,Col3=1},
};

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

foreach (var x in Query)
{
    Console.WriteLine("{0},{1}", x.Value, x.Count);
}

Result:

Value Count     
A      1  
B      2  
C      3

Upvotes: 2

Yograj Gupta
Yograj Gupta

Reputation: 9869

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

Upvotes: 8

Mayank
Mayank

Reputation: 8852

var dictionary = list.GroupBy(str => str.Col1)
    .ToDictionary(group => group.Key, group => group.Count());

from here

Upvotes: 6

Alastair Pitts
Alastair Pitts

Reputation: 19591

Have a look into using the .GroupBy() LINQ method on col1. You can then use .Count() on the resulting groups to determine how many are in each group.

Upvotes: 3

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

You can use GroupBy for that.

var groupedlist = list.GroupBy(c => c.Col1)
                      .Select((key, c) => new {Value = key, Count = c.Count()});

Upvotes: 8

Related Questions