Remove nulls from a list using the C# component in Grasshopper

This simple script removes nulls from a list in Grasshopper. It preserves all data types and other data that you pass through it.

remove-nulls-grasshopper

To set up, copy the code below into a standard C# component in Grasshopper. Set input x as a list. Feed your list into x. The return ‘A’ will return the list x with nulls removed.

    var rtnlist = new List<object>();

    foreach (object obj in x)
    {
      if (obj != null) rtnlist.Add(obj);
    }

    A = rtnlist;

The other C# (counting nulls) in the image came from this post.

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;