Array tricks I seem to forget

Having developed in C and VB6 at the start of my career there is a definite habit of creating utility modules that help with the manipulation of strings or processing arrays. I have noted from time to time that this has made me neglect some of the in built language features of my primary language, C#.

My first instinct when dealing with an array in C# is to loop through it to create and find strings. I am placing both of these string\array examples here to remind me to stop reinventing the wheel!

Example 1 - Creating a comma (or whatever) separated list of strings from an array.

string[] values = new string[5];
values[0] = "1";
values[1] = "2";
values[2] = "3";
values[3] = "4";
values[4] = "5";
string val = String.Join(",", values); //val = "1,2,3,4,5" - I believe Join had a VB6 equivalent

Example 1 - Search an array for a specific value

string stringvals = "1,2,3,4,5";
string [] values;
int searchresult;

values = stringvals.Split(','); // again a VB 6 equivalent was available
searchresult = Array.BinarySearch(values,"4"); //returns a negative number if it cannot find the value.

Technorati tags: ,


Comment Section

Comments are closed.