A C# component for Grasshopper showing how lists of repeating items can be consolidated into unique items, with counts of each

Count the number of repeated strings in a list in Grasshopper

This script takes in a list of strings. It consolidates repeated values and tells you how many times equal strings are repeated.

string-histogram-grasshopper

To use, copy the code below into a standard C# script component in Grasshopper. Add an additional output called B. Output A will show all the different values found in the list, and B will show the count for each item in A for the number of times that item was found.

    var names = new List<string>();
    var counts = new List<int>();

    foreach (string str in x)
    {
      bool exists = false;
      for (int i = 0; i < names.Count; i++)
      {
        if(str == names[i])
        {
          exists = true;
          counts[i]++;
        }
      }
      if (!exists)
      {
        counts.Add(1);
        names.Add(str);
      }

    }
    A = names;
    B = counts;

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: