Pa1
Pa1

Reputation: 630

How to get the count of the values that are repeated in c#

I want to find the no of integers that are repeated using linq query. for eg my list consists of

var array = new int[]{1,1,1,2,2,2,2,3,3,9,9,16,16};

Now i want to query like i want to get the count of 1 as 3 count of 2 as 4 count of 3 as 2 count of 9 as 2 count of 16 as 2

How can i do that using linq in c#. Hope you understand my question.

Upvotes: 0

Views: 3801

Answers (6)

Nitish Kakkar
Nitish Kakkar

Reputation: 51

Using Linq:

var NumArray= new int[] { 1, 1, 1, 2, 2, 2, 2, 3, 3, 9, 9, 16, 16 };
var counts = NumArray.GroupBy(item => item)
                     .Select(a=>new {Number=a.Key,Count =a.Count()});

Upvotes: 1

Dave Bish
Dave Bish

Reputation: 19656

Easy, using LINQ's GroupBy

var numbers = new int[] { 1, 1, 1, 2, 2, 2, 2, 3, 3, 9, 9, 16, 16 }; 

var counts = numbers
    .GroupBy(item => item)
    .Select(grp => new { Number = grp.Key, Count = grp.Count() });

Result:

Number    Count
1         3 
2         4 
3         2 
9         2 
16        2 

Upvotes: 13

Soner Gönül
Soner Gönül

Reputation: 98858

var array = new int[] {1,1,1,2,2,2,2,3,3,9,9,16,16}; 

var query = from x in array
            group x by x into g
            orderby count descending
            let count = g.Count()
            select new {Value = g.Key, Count = count};

foreach (var i in query)
{
    Console.WriteLine("Value: " + i.Value + " Count: " + i.Count);
}

Result will be;

Value: 1 Count: 3
Value: 2 Count: 4
Value: 3 Count: 2
Value: 9 Count: 2
Value: 16 Count: 2

Here is a DEMO.

Upvotes: 0

cuongle
cuongle

Reputation: 75326

You can use LINQ GroupBy then Count on each group:

var dic = array.GroupBy(x => x)
               .ToDictionary(g => g.Key, g => g.Count());

In here, ToDictionary is used so you can access to Dictionary get Count with better performance if you have large list and need to access often:

int count1 = dic[1]; //count of 1

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

Use GroupBy + Count

var groups = array.GroupBy(i => i);

foreach(var group in groups)
    Console.WriteLine("Number: {0} Count:{1}", group.Key, group.Count());

Note that you need to add using System.Linq;.

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

array.GroupBy(x => x)
     .Select(g => new {
                       Val = x.Key,
                       Cnt = x.Count()
                      }
            );

Upvotes: 1

Related Questions