Array to List C#

using System; using System.Text; using System.Collections.Generic; using System.Linq; namespace forgetCode { class program { public static void Main[] { string [] array = { "hi","welcome", "to", "forget code"}; List list = array.ToList[]; foreach [string item in list] { Console.WriteLine[item]; } } } }

C# Convert List to ArrayUse the ToArray and ToList methods to convert Lists and arrays.

Convert List, array. A List can be converted to an array. The opposite conversion is also possible. In each conversion, the element types remain the same—strings remain strings.

More complex methods can be implemented. A for-loop can copy elements from a List and add them to an array. But this is more work for the programmer.

List to array. Here we convert a string List into a string array of the same number of elements. At the end, the program prints the array's length.

Step 1 We create a List and populate it with some strings. The List here can only hold strings [or null].

List

Step 2 Next we use ToArray on the List. To test it, we pass the string array to the Test[] method.

ToArray

Array

C# program that converts List to array

using System; using System.Collections.Generic; class Program { static void Main[] { // Step 1: create list. List list = new List[]; list.Add["one"]; list.Add["two"]; list.Add["three"]; list.Add["four"]; list.Add["five"]; // Step 2: convert to string array. string[] array = list.ToArray[]; Test[array]; } static void Test[string[] array] { Console.WriteLine["Array received: " + array.Length]; } }Array received: 5

Array to List. We can convert an array of any number of elements to a List that has the same type of elements. There are 3 parts to this example.

Part 1 Here we initialize a new string array containing 5 strings. These are specified as string literals.

Part 2 Here we convert the array to a List with the List constructor. This returns a new List of strings.

Part 3 Here the example converts the array to a List with the ToList[] instance method.

C# program that uses List constructor and ToList

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main[] { // Part 1: string array. string[] array = new string[] { "one", "two", "three", "four", "five" }; // Part 2: use list constructor. List list1 = new List[array]; Test[list1]; // Part 3: use ToList method. List list2 = array.ToList[]; Test[list2]; } static void Test[List list] { Console.WriteLine["List count: " + list.Count]; } }List count: 5 List count: 5

Implicit conversion error. You may get the "Cannot implicitly convert type" error. This error raised by the compiler tells you that the type needs a regular cast or is not compatible.

Note If your code statement tries to assign a List to an array, you will get this error.

C# program that causes convert type error

using System.Collections.Generic; class Program { static void Main[] { List items = null; int[] result = new int[0]; // This does not work. items = result; } }Error CS0029 Cannot implicitly convert type 'int[]' to 'System.Collections.Generic.List'

Notes, ToList. The ToList method is an extension method from System.Linq. This kind of method is an addition to normal C# method calls.

ToList

Extension

Readability. It is easy to remember that ToList converts a collection to a List, and ToArray does the same for an array. These methods are well-named.

A summary. Convert arrays to Lists [and lists to arrays] with this code. We can not just as sign one to the other. The List constructor can also be used—and it avoids a null check].

© 2007-2022 sam allen.

see site info on the changelog.

In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically. It is the same as Array except that its size increases dynamically.

An ArrayList can be used to add unknown data where you don't know the types and the size of the data.

Create an ArrayList

The ArrayList class included in the System.Collections namespace. Create an object of the ArrayList using the new keyword.

using System.Collections; ArrayList arlist = new ArrayList[]; // or var arlist = new ArrayList[]; // recommended

Adding Elements in ArrayList

Use the Add[] method or object initializer syntax to add elements in an ArrayList.

An ArrayList can contain multiple null and duplicate values.

// adding elements using ArrayList.Add[] method var arlist1 = new ArrayList[]; arlist1.Add[1]; arlist1.Add["Bill"]; arlist1.Add[" "]; arlist1.Add[true]; arlist1.Add[4.5]; arlist1.Add[null]; // adding elements using object initializer syntax var arlist2 = new ArrayList[] { 2, "Steve", " ", true, 4.5, null };

Use the AddRange[ICollection c] method to add an entire Array, HashTable, SortedList, ArrayList, BitArray, Queue, and Stack in the ArrayList.

var arlist1 = new ArrayList[]; var arlist2 = new ArrayList[] { 1, "Bill", " ", true, 4.5, null }; int[] arr = { 100, 200, 300, 400 }; Queue myQ = new Queue[]; myQ.Enqueue["Hello"]; myQ.Enqueue["World!"]; arlist1.AddRange[arlist2]; //adding arraylist in arraylist arlist1.AddRange[arr]; //adding array in arraylist arlist1.AddRange[myQ]; //adding Queue in arraylist

Accessing an ArrayList

The ArrayList class implements the IList interface. So, elements can be accessed using indexer, in the same way as an array. Index starts from zero and increases by one for each subsequent element.

An explicit casting to the appropriate types is required, or use the var variable.

var arlist = new ArrayList[] { 1, "Bill", 300, 4.5f }; //Access individual item using indexer int firstElement = [int] arlist[0]; //returns 1 string secondElement = [string] arlist[1]; //returns "Bill" //int secondElement = [int] arlist[1]; //Error: cannot cover string to int //using var keyword without explicit casting var firstElement = arlist[0]; //returns 1 var secondElement = arlist[1]; //returns "Bill" //var fifthElement = arlist[5]; //Error: Index out of range //update elements arlist[0] = "Steve"; arlist[1] = 100; //arlist[5] = 500; //Error: Index out of range

Iterate an ArrayList

The ArrayList implements the ICollection interface that supports iteration of the collection types. So, use the foreach and the for loop to iterate an ArrayList. The Count property of an ArrayList returns the total number of elements in an ArrayList.

ArrayList arlist = new ArrayList[] { 1, "Bill", 300, 4.5F }; foreach [var item in arlist] Console.Write[item + ", "]; //output: 1, Bill, 300, 4.5, for[int i = 0 ; i < arlist.Count; i++] Console.Write[arlist[i] + ", "]; //output: 1, Bill, 300, 4.5,

Insert Elements in ArrayList

Use the Insert[] method to insert an element at the specified index into an ArrayList.

Signature: void Insert[int index, Object value]

ArrayList arlist = new ArrayList[] { 1, "Bill", 300, 4.5f }; arlist.Insert[1, "Second Item"]; foreach [var val in arlist] Console.WriteLine[val];

Use the InsertRange[] method to insert a collection in an ArrayList at the specfied index.

Signature: Void InsertRange[int index, ICollection c]

ArrayList arlist1 = new ArrayList[] { 100, 200, 600 }; ArrayList arlist2 = new ArrayList[] { 300, 400, 500 }; arlist1.InsertRange[2, arlist2]; foreach[var item in arlist1] Console.Write[item + ", "]; //output: 100, 200, 300, 400, 500, 600,

Use the Remove[], RemoveAt[], or RemoveRange methods to remove elements from an ArrayList.

ArrayList arList = new ArrayList[] { 1, null, "Bill", 300, " ", 4.5f, 300, }; arList.Remove[null]; //Removes first occurance of null arList.RemoveAt[4]; //Removes element at index 4 arList.RemoveRange[0, 2];//Removes two elements starting from 1st item [0 index]

Check Element in ArrayList

Use the Contains[] method to determine whether the specified element exists in the ArrayList or not. It returns true if exists otherwise returns false.

ArrayList arList = new ArrayList[] { 1, "Bill", 300, 4.5f, 300 }; Console.WriteLine[arList.Contains[300]]; // true Console.WriteLine[arList.Contains["Bill"]]; // true Console.WriteLine[arList.Contains[10]]; // false Console.WriteLine[arList.Contains["Steve"]]; // false

It is not recommended to use the ArrayList class due to performance issue. Instead, use List to store heterogeneous objects. To store data of same data type, use Generic List.

ArrayList Class

The following diagram illustrates the ArrayList class.

C# ArrayList

ArrayList Properties

Properties Description
Capacity Gets or sets the number of elements that the ArrayList can contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly Gets a value indicating whether the ArrayList is read-only.
Item Gets or sets the element at the specified index.

ArrayList Methods

Methods Description
Add[]/AddRange[] Add[] method adds single elements at the end of ArrayList.
AddRange[] method adds all the elements from the specified collection into ArrayList.
Insert[]/InsertRange[] Insert[] method insert a single elements at the specified index in ArrayList.
InsertRange[] method insert all the elements of the specified collection starting from specified index in ArrayList.
Remove[]/RemoveRange[] Remove[] method removes the specified element from the ArrayList.
RemoveRange[] method removes a range of elements from the ArrayList.
RemoveAt[] Removes the element at the specified index from the ArrayList.
Sort[] Sorts entire elements of the ArrayList.
Reverse[] Reverses the order of the elements in the entire ArrayList.
Contains Checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.
Clear Removes all the elements in ArrayList.
CopyTo Copies all the elements or range of elements to compitible Array.
GetRange Returns specified number of elements from specified index from ArrayList.
IndexOf Search specified element and returns zero based index if found. Returns -1 if element not found.
ToArray Returns compitible array from an ArrayList.

  • Share
  • Tweet
  • Share
  • Whatsapp

Video liên quan

Chủ Đề