Using ConvertAll to Convert a Set of Values
ConvertAll is one of those methods that is not used very often, but when you need it, it is very useful. It converts all of the elements of one list or array into element of another type.
In this example the user enters a list of numbers into a TextBox as a string, that list is converted to a list of integers, and the integers are averaged.
string numbers = textBox1.Text;
var stringArray = numbers.Split(‘,’);
var numberArray = Array.ConvertAll(stringArray,
s => int.TryParse(s, out value) ? value : 0);
MessageBox.Show("Average is: " + numberArray.Average());
Dim numbers As String = TextBox1.Text
If Not String.IsNullOrEmpty(numbers) Then
Dim stringArray = numbers.Split(","c)
Dim value As Integer
Dim numberArray = Array.ConvertAll(stringArray,
Function(s) If(Integer.TryParse(s, value), value, 0))
MessageBox.Show("Average is: " & numberArray.Average())
This code resides in a Button Click event for a Windows form that contains a TextBox and a Button. The user enters a set of numbers into the TextBox, separated by commas, and clicks the button.
The code uses the Split function to split the entered string of numbers into an array using the comma as the separator.
The Array.ConvertAll method converts the resulting string array into an integer array using the Integer.TryParse method. If the value can be parsed to an integer, it uses the value. If not, it uses a zero. This protects the code from invalid user input.
Finally, it uses the Average method to calculate the numeric average of the resulting list.
Use this technique any time you have a list or array of values and need to convert them all to another type.