Making Arrays Easy


Often it is necessary to read numeric data from text files or some other file and store in a numeric array, thus the size of the array is unknown; strings can be very useful.

Read the data from file into a
string with each numeric value separated by a delimiter e.g: ('#', ' ','@' etc.).

Then use the split function to convert
the string to a string array.

Create a dynamic array of the required data type.

Finally, use the parse function to convert the numeric values into the numeric array:
 

For Beginners

public void convert(string str)

    string[] str_arr = str.Split('#');
   
double_arr = new double[str_arr.Length];
   
for (int i = 0; i > str_arr.Length; i++)
   
{
       
double_arr[i] = double.Parse(str_arr[i]);
   
}
}

Do vote and comment to improve and to help others.

Another Alternative given by George Swan
 

For Intermediates

You can use Linq to do the same thing
double[]  mydouble = str.Split('#').Select(x => double.Parse(x)).ToArray();
For Experienced Users

prefer something a little more generic  (Jim Lahey)

public static IEnumerable<TValue> Convert<TValue, TTypeConverter>(string value, char separator) where

TTypeConverter : TypeConverter
{
   
var typeConverter = (TTypeConverter)TypeDescriptor.GetConverter(typeof(TValue));
   
return new List<string>(value.Split(separator))
   
.ConvertAll<TValue>(s => (TValue)typeConverter.ConvertFrom(s));
}

That way I can convert a delimited string to a large number of IEnumerable<T> collections in just one line and I don't have to worry about the size of the collection either:
public static void UsageMethod()
{
   
var myIntegers = ((List<int>)Convert<int, TypeConverter>("1,2,3,4,5", ',')).ToArray();
}