TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Array.ConvertAll, Change Type of Elements

Use Array.ConvertAll method to transform the type of all elements in an array.
Array.ConvertAll converts an entire array. It converts all elements in one array to another type. We specify the conversion function—this can be done in the lambda expression syntax form.
Example. To begin, this example program creates an integer array of 3 elements on the managed heap. Then, we invoke the Array.ConvertAll static method. You do not need to specify the type parameters, as they are inferred statically.Static

Lambda: The second argument to Array.ConvertAll is a lambda expression. The lambda returns the ToString() method result on the element.

Generic Class, MethodToString
C# program that uses Array.ConvertAll method using System; class Program { static void Main() { // Integer array of 3 values. int[] array1 = new int[3]; array1[0] = 4; array1[1] = 5; array1[2] = 6; // Use ConvertAll to convert integer array to string array. string[] array2 = Array.ConvertAll(array1, element => element.ToString()); // Write string array. Console.WriteLine(string.Join(",", array2)); } } Output 4,5,6
Internals. How does the Array.ConvertAll method work inside? First, the second argument can be considered a higher-order procedure. This argument is called each time an element is to be converted.

Note: The ConvertAll method allocates a new array and then places the result of the converter method into each corresponding element slot.

It would be faster to write an imperative method. This would eliminate the delegate method invocations (which are more expensive than regular methods) and the slight overhead that occurs with argument checking.
Summary. The Array.ConvertAll method allows you to declaratively convert an entire array with a single statement. It incurs some performance overhead. But it can simplify code, particularly in programs where many different conversions take place.Array
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf