Print elements in format 'x,y,z; x,y,z; ...' - CSharp System.Collections

CSharp examples for System.Collections:IEnumerable

Description

Print elements in format 'x,y,z; x,y,z; ...'

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from   w w w . j a v  a 2 s.  co m

public class Main{
        /// <summary>
        /// Print elements in format 'x,y,z; x,y,z; ...'
        /// </summary>
        /// <param name="array"></param>
        /// <param name="components">2, 3, or 4.</param>
        /// <returns></returns>
        public static string PrintVectors(this float[] array, int components = 3)
        {
            if (components < 1) { throw new ArgumentOutOfRangeException("components"); }

            if (array == null) { return string.Empty; }

            StringBuilder builder = new StringBuilder();
            int counter = 0;
            foreach (var item in array)
            {
                builder.Append(item.ToShortString());
                counter++;
                if (counter % components == 0)
                { 
                    builder.Append("; ");
                    counter = 0;
                }
                else
                { 
                    builder.Append(", "); 
                }
            }

            return builder.ToString();
        }
}

Related Tutorials