70

Is there a simple way to count the number of occurrences of all elements of a list into that same list in C#?

Something like this:

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

string Occur;
List<string> Words = new List<string>();
List<string> Occurrences = new List<string>();

// ~170 elements added. . . 

for (int i = 0;i<Words.Count;i++){
    Words = Words.Distinct().ToList();
    for (int ii = 0;ii<Words.Count;ii++){Occur = new Regex(Words[ii]).Matches(Words[]).Count;}
         Occurrences.Add (Occur);
         Console.Write("{0} ({1}), ", Words[i], Occurrences[i]);
    }
}

9 Answers 9

119

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

3
  • 1
    +1. this is very elegant to count the occurrence of each distinct elements.
    – Stan R.
    Commented Jul 16, 2009 at 18:01
  • 1
    FindAll returns a list of elements from the original list that match a predicate, so you would have to do it once for each unique element to find the count for that element.
    – JP Alioto
    Commented Jul 16, 2009 at 18:18
  • 1
    Just use it. Great solution. If you want to sort it, just use : var g = l1.GroupBy( i => i ).OrderByDescending(group => group.Count());.
    – aloisdg
    Commented Apr 28, 2014 at 18:44
25

You can do something like this to count from a list of things.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

To count a single element

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();
4
  • 1
    +1: It took me awhile to figure out that GetMethods() was just your list of things. :) Commented Jul 16, 2009 at 18:05
  • yeah, I thought of that and decided to make it more readable. thanks, although I misread the question. It says to count "all the element"..ooops. This should still be useful enough.
    – Stan R.
    Commented Jul 16, 2009 at 18:06
  • @StanR. - this solution works for my problem. However, is there a method on the list where I can count the occurrence greater than or equal to in words? I am using "int" type instead of "string." Commented Mar 1, 2017 at 16:07
  • @MihirPatel just change the .Where to x > num || x == num
    – Stan R.
    Commented Mar 1, 2017 at 18:50
15
var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

0
3
public void printsOccurences(List<String> words)
{
    var selectQuery =
        from word in words
        group word by word into g
        select new {Word = g.Key, Count = g.Count()};
    foreach(var word in selectQuery)
        Console.WriteLine($"{word.Word}: {word.Count}");*emphasized text*
}
1

This is a version which avoids Linq but uses only slightly more code.

// using System.Collections.Generic;

Dictionary<int, int> oGroups = new Dictionary<int, int>();
List<int> oList = new List<int>() { 1, 2, 3, 4, 5, 2, 2, 2, 4, 4, 4, 1 };

foreach (int iCurrentValue in oList)
{
    if (oGroups.ContainsKey(iCurrentValue))
        oGroups[iCurrentValue]++;
    else
        oGroups.Add(iCurrentValue, 1);
}

foreach (KeyValuePair<int, int> oGroup in oGroups)
{
    Console.WriteLine($"Value {oGroup.Key} appears {oGroup.Value} times.");
}
1
        List<int> list = new List<int>()
        { 1,2,3,4,5,2,2,2,1           
        };

        //int a=0

        var a = list.GroupBy(x => x) ;

        foreach (var y in a)
        {
            Console.WriteLine("The element" + y.Key);
            Console.WriteLine(y.Count());
        }
1
  • Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation? Commented Sep 14, 2023 at 7:06
0

this code returns a dictionary that contain the world and the occurrence:

            var wordsDic = Words
            .GroupBy(p => p)
            .ToDictionary(p => p.Key, q => q.Count());
0

I came here in hopes that counting occurrences would be an easy solution to what I wanted to do, which is find if any duplicates exists. (More about this below.) I tried to find a solution without linq or multiple loops.

The code:

using System;
using System.Collections.Generic;

List<string> Words = new List<string>();
List<int> Occurrences = new List<int>();

// ~170 elements added...
// Note: Occurrences is still empty at this point

string[] Done = new string[Words.Count];
for (int i = 0; i < Done.Length; i++)
{
    if (Array.IndexOf(Done, Words[i]) is int f && f > -1)
    {
        for (int o = 0; o < Done.Length; o++)
        {
            int d = Array.IndexOf(Done[o..], Words[i]);
            if (d == -1) { break; }
            Occurrences[o+d] += 1;
            o += d;
        }
        Occurrences.Add(Occurrences[f]);
    }
    else
    {
        Occurrences.Add(1);
    }
    Done[i] = Words[i];
}

// To write the result as seen in the question
for (int i = 0; i < Done.Length; i++)
{
    Console.Write("{0} ({1}), ", Words[i], Occurrences[i]);
}

Explanation:

The core is the nested for loop that checks for all occurrences, using IndexOf, and the range struct. Here we have:

  • Done which is an array that lists all previously checked items from the list
  • o which is the index of the for loop, indicating the last occurrence +1 (o++), starting at 0
  • d which is the index of the first duplicate of the current item in Done
  • A command that increases o with d, if found, so that the next IndexOf search continues with the next occurrence.
  • A command that increases the occurrence count at index o+d by 1. We need to add o to d, because d is the index starting at o (range).
  • A break command to end the loop if no more occurrences are found.

Up in the hierarchy, there is a check, whether there are any previous duplicates of the current item in Done, so that we can add 1 to the occurrences list, if there are no previous occurrences. Here, we have:

  • f which is the index of the first occurrence found in Done
  • If not found, the value is -1, otherwise bigger (index). This is implemented in the if/else expression.
  • If found, in addition to increasing the count value of all previous occurrences, as stated above, the same value (total current occurrences) is also added to the occurrence list.
  • If not found, a value of 1 (1 occurrence, the current item) is added to the list.

Finally, the main loop, which is the loop through all items in the Words list.

  • Each word has an index i that corresponds to the Done array index, because the array has the same size.
  • At the last step of the loop, the item is added to the Done array, so it can now be found as a duplicate, and its count can be updated.

Notes:

  • This will include the occurrence (count) of each word accurately, but all, even duplicates.
  • It would be better to remove duplicate occurrence in the count results, as other solutions do it (distinct). Such an implementation would make the code simpler, since only one value has to be increased, so instead of the inner loop, a single IndexOf would be enough. Just be sure to also add the items to an item list, so that this new list matches the reduced count list (or use a dictionary or list with value and count property for each item).
  • Depending on duplicate occurrences, this is arguably worse than two loops, where the first one gives a distinct, shorter list, where each item then is counted in a second loop. I'm not one who has much insight into this, however.

As a bonus, here is what I took as a base, which is to find if any duplicates exist.

I have a class with a Clash property and a separate variable that checks if any clashes exist. My class has a Number property, which I want to check for duplicates. Here's what I came up with:

// My list to check for duplicates, obviously added some items to it
List <MyClass> MyList = new List <MyClass> ();

// My variable that indicates whether any duplicates exist
bool Clash;

Clash = false;
string[] Check = new string[MyList.Count];
for (int i = 0; i < Check.Length; i++)
{
    if (MyList[i] is MyClass MC && MC.Number is string N)
    {
        MC.Clash = Array.IndexOf(Check, N) is int d && d > -1;
        MyList[d].Clash = MC.Clash;
        Clash = MC.Clash || Clash;
        Check[i] = N;
    }
}

I don't need the inner for loop, because the initial list itself has the clash property that I want to update. If the list had a count (int) item property, instead of clash, we could use a similar code for the count purpose as well.

-3

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.