Split a string into array and count the values

Kristin Ray-Sprenger asked on August 30, 2016 23:26

Hi there, I am working on a form validation macro that will count the number of checkboxes checked and limit it to 3 or fewer. I've tried using Count to determine how many elements are in the array but it doesn't return anything. Here's my code:

{%
StringIs = "Functional Metal Fabrication|Design & Graphic Technology|Printed Technology Piece|Creative Metal Fabrication"; 
return StringIs.Split("|").Count;
#%}

Recent Answers


Chetan Sharma answered on August 31, 2016 05:59

Aren't you using count as an attribute rather than a method. I think in your case .length or .count() should work

0 votesVote for this answer Mark as a Correct answer

Anton Grekhovodov answered on August 31, 2016 07:04 (last edited on December 10, 2019 02:30)

Hi Kristin,

There isn't a method or property to return items count. But you can use the following macro code:

{% z=0; foreach(x in "1|2|".Split("|", true)) {z += 1;}; return z; |(identity)GlobalAdministrator%} //return 3 

The second parameter of Split method is a SplitOption, if it's true, the empty entries will be removed, if it's false (default value), the empty entries will be counted.

2 votesVote for this answer Mark as a Correct answer

Kristian Bortnik answered on August 31, 2016 12:50 (last edited on December 10, 2019 02:30)

As Anton mentioned, there is no built-in method or property for the count of items in an array.

However, you could write a quick macro method to accomplish this:

[assembly: RegisterExtension(typeof(ArrayMacroMethods), typeof(Array))]
public class ArrayMacroMethods : MacroMethodContainer
{
    [MacroMethod(typeof(int), "Returns the number of items in an array.", 1)]
    [MacroMethodParam(0, "countedarray", typeof(Array), "Array to count items in.")]
    public static object Count(EvaluationContext context, params object[] parameters)
    {
        if (parameters.Length != 1)
            throw new NotSupportedException();

        var array = parameters[0] as Array;
        if (array == null)
            throw new NotSupportedException();

        return array.Length;
    }
}

Then it's just a matter of using it as an extension method:

{%
StringIs = "Functional Metal Fabrication|Design & Graphic Technology|Printed Technology Piece|Creative Metal Fabrication"; 
return StringIs.Split("|").Count();
|(identity)GlobalAdministrator%}
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.