C arraylist LEARNOVITA

ArrayList Collection on in C# | A Complete tutorial For Beginners

Last updated on 12th Aug 2022, Blog, Tutorials

About author

Manish Kiran (C# Developer )

Manish Kiran is a C# Developer expert and subject specialist who have experience with Git, WPF, WinForms, C#,.Net, SQL, .NET Development, VB.NET Framework, .NET Core, SVN, Mercurial. His articles help the learners to get insights about the Domain.

(5.0) | 18954 Ratings 2057

Introduction to ArrayList assortment on in C#

In C #, AN ArrayList may be a non-normal series of dynamically developing objects. it’s like AN array, besides that its length can increase dynamically. If you don’t recognise the sort and length of your information, you may use ArrayList to feature unknown information.

ArrayList

ArrayList magnificence contained withinside the System.Collections namespace. produce AN ArrayList item the usage of the key-word new.

Create AN ArrayList

  • Use System.Collections.
  • ArrayList list = new ArrayList ();
  • // or
  • var list = new ArrayList (); // counseled to feature factors to ArrayList

Add AN detail to the ArrayList the usage of the Add () technique or the item initialisation syntax. The ArrayList will embrace quiet one null and replica values.

Example: Adding AN detail to AN ArrayList

  • // Add AN detail the usage of the ArrayList.Add () technique
  • ar arlist1 = new ArrayList ();
  • arlist1.Add (1);
  • arlist1.Add (“invoice”);
  • arlist1.Add (“”);
  • arlist1.Add (true);
  • arlist1.Add (4.5);
  • arlist1.Add (null);
  • // Add AN detail the usage of the item initialisation syntax
  • var arlist2 = new ArrayList ()
  • ;

Use the AddRange (ICollection c) methodology to feature AN Array, HashTable, SortedList, ArrayList, BitArray, Queue, and therefore the entire Stack to AN ArrayList

What are Collections in C#?

  • An assortment may be a bunch of objects of comparative kind that we would perform tasks like supplement, erase, update, sort, etc.
  • Collections, contrasted with clusters, are a more practical strategy for taking care of a bunch of connected things or articles.
  • The objective of this text is to direct you on the most effective thanks to utilize Collections (type) within the C# programming language.
  • Collections are usually wont to cope with and cope with a bunch of comparative data varieties. Clusters are likewise wont to superintend comparative styles of data, nevertheless Collections supply further ability once managing assembled things of assorted types.

Kinds of Collections

Kind Of Collection In Array

C# Collections are sorted into 3 principle namespaces:

  • System.Collections.Generic classes (Generic)
  • System.Collections.Concurrent classes (Concurrent)
  • System.Collections classes (Non-Generic)
  • To add components to an assortment, we proclaim an occurrence of a class.

For instance, when we are utilizing components of similar information type, we proclaim System.Collections.Generic namespace which will import every one of the necessary classes.

System.Collections.Generic classes (Generic). On the off chance that the components are of similar information type, we utilize one of the classes in the System.Collections.Generic namespace. The nonexclusive assortment just acknowledges one information type and no different information type

The classes given by the Generic Collections include:

  • List
  • Stack
  • Line
  • LinkedList
  • HashSet
  • SortedSet
  • Word reference
  • SortedDictionary
  • SortedList
  • System.Collections.Concurrent classes (Concurrent)

Simultaneous Collections are upheld in the .NET Framework 4 with the System.Collections.Concurrent namespace. They assist with admittance to assortment objects from a few strings. Assuming many strings need to get to an assortment simultaneously, the simultaneous Collections ought to be utilized rather than non-conventional and nonexclusive Collections.

The classes given by the simultaneous Collections include:

  • BlockingCollection
  • ConcurrentBag
  • ConcurrentStack
  • ConcurrentQueue
  • ConcurrentDictionary
  • Partitioner
  • OrderablePartitioner
  • System.Collections classes (Non-Generic)

Dissimilar to the conventional assortment, non-non exclusive Collections acknowledge components of various information types and use the System.Collections namespace. The classes given by the Non-Generic Collections include:

  • ArrayList
  • Stack
  • Line
  • Hashtable

Examples

  • Add the entire Array / ArrayList to 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); // Add arraylist to arraylist
  • arlist1.AddRange (arr); // Add array to arraylist
  • arlist1.AddRange (myQ); // Add queue to ArrayList Access to ArrayList
  • The ArrayList class implements the IList interface. Therefore, elements can be accessed using an indexer just like an array. The index starts at zero and increments by 1 for each subsequent element. Explicit cast to the appropriate type is required. Alternatively, use the var variable

    Constructors:

    ArrayList()

    Initializes a new instance of the ArrayList class that is empty and has the default initial capacity.

    ArrayList(ICollection)

    Initializes a new instance of the ArrayList class that contains elements copied from the specified collection and that has the same initial capacity as the number of elements copied.

    ArrayList(Int32)

    Initializes a new instance of the ArrayList class that is empty and has the specified initial capacity

    Example: Accessing elements of ArrayList

    Elements Of ArrayList
  • var list = new ArrayList ()
  • {
  • 1,
  • “Bill”,
  • 300,
  • 4.5f
  • };
  • // Access a single item with the indexer
  • int firstElement = (int) arlist [0]; // Returns 1
  • string secondElement = (string) arlist [1]; // Returns the “invoice”.
  • // int secondElement = (int) arlist [1]; // Error: Unable to cast string to int
  • // Use var keyword without explicit casting
  • var firstElement = arlist [0]; // returns 1
  • var secondElement = list [1]; // Returns the “invoice”.
  • // var fiveElement = list [5]; // Error: Index out of range
  • // Update item
  • arlist [0] = “Steve”;
  • artists [1] = 100;
  • // Arlist [5] = 500; // Error: Index out of range
  • ArrayList iterator

    ArrayList implements an associated ICollection interface that supports collection-type iterations. Therefore, retell over the ArrayList victimization foreach and for loops. The Count property of the ArrayList returns the overall variety of components within the ArrayList.

    Example:

  • Iterate ArrayList
  • ArrayList list = new ArrayList ()
  • ;
  • Console.Write (item + “,”); // Output: one, Bill, 300, 4.5,
  • for (int i = 0; i
  • Insert components into ArrayList
  • Use the Insert () technique to insert a part into associate ArrayList with the desired index.
  • Points to recall

    • An ArrayList is an assortment of varied varieties of things.
    • The distinction between an ArrayList associated with a cluster is that an ArrayList is dynamic in size and supports totally different element sorts.
    • An ArrayList will be introduced with introduction punctuation. That’s to mention, comma isolated qualities in an exceedingly code block.
    • We can get to elements in associate ArrayList with the trained worker, or with circles.
    • Since associate ArrayList is dynamic in size, we have a tendency to utilize the Add() and AddRange() capacities to affix new things to the summary.
    • The Add() capability can enhance the end of the ArrayList.
    • The AddRange() can add various things, such as a cluster or assortment, to the furthest limit of the ArrayList.

    The following figure shows the ArrayList category.

    • C # ArrayList
    • ArrayList property
    • Property description
    • Gets or sets the quantity of components that the CapacityArrayList will hold.
    • Gets the quantity of components really contained within the CountArrayList.
    • Gets a worth that indicates whether or not the dimensions of the IsFixedSizeArrayList is fastened.
    • Gets a worth that indicates whether or not IsReadOnlyArrayList is read-only.
    • Item Gets or sets associate item at the desired index. ArrayList technique

    Method description

    The Add () / AddRange () Add () strategies add individual components to the tip of the ArrayList. The AddRange () technique adds all the weather of the desired assortment to the ArrayList. The Insert () / InsertRange () Insert () technique inserts one component into the ArrayList at the desired index.

    The InsertRange () technique inserts all the weather of the desired assortment into the ArrayList, beginning at the desired index. The takeaway () / take awayRange () Remove () technique removes the desired component from the ArrayList. The RemoveRange () technique removes the variety of components from the ArrayList. RemoveAt () Removes the component at the desired index from the ArrayList. type () types the whole component of ArrayList. Reverse () Reverses the order of the weather within the entire ArrayList. Checks if the desired component it contains exists within the ArrayList.Clear Deletes all components within the ArrayList. CopyTo Copies all components or a variety of components into a compatible array. Returns the desired variety of components from the desired index of GetRangeArrayList. IndexOf Searches for the desired item and returns a zero-based index if found.

    The following example shows however that associate ArrayList is formed and initialized, and its values are displayed.

  • C #
  • With system;
  • Use System.Collections.
  • public category SamplesArrayList
  • produce and initialize a brand new ArrayList.
  • ArrayList myAL = new ArrayList ();
  • myAL.Add (“Hello”);
  • myAL.Add (“World”);
  • myAL.Add (“!”);
  • // Show ArrayList properties and values increase.
  • Console.WriteLine (“myAL”)
  • Console.WriteLine (“
  • Count:
  • ”, myAL.Count);
  • Console.WriteLine (“
  • Capacity: ”, myAL.Capacity);
  • Console.Write (“
  • value:”);
  • PrintValues (myAL);
  • }
  • public static void PrintValues(IEnumerable myList)
  • {
  • foreach (Object obj in myList)
  • Console.Write (“
  • ”, obj);
  • Console.WriteLine ();
  • }
  • }
  • / *
  • This code produces output like the following:
  • myAL
  • Count:
  • 3
  • Capacity: four
  • Value:
  • Hello
  • World
  • !
  • * /
  • Using the ArrayList category

    Using the Arraylist Category

    We don’t advocate victimization of the ArrayList category for brand new development. we tend to advocate that you simply use the generic List category instead. The ArrayList category is meant to store a heterogeneous assortment of objects. However, it’s not perpetually the simplest performance. Instead, we tend to advocate the following: For a heterogeneous assortment of objects, use List & lt; Object & gt ;. kind (for C #) or List (Of Object) (for Visual Basic).Use the List category for similar collections of objects. For an outline of the relative performance of those categories, see “Performance Considerations” within the List Reference topic. For general data on the way to use generic assortments rather than non-generic collection varieties, see Don’t use non-generic collections on GitHub.

    ArrayList isn’t certain to be sorted. you need to kind the ArrayList by business the kind technique before playacting any operation that needs sorting the ArrayList (such as BinarySearch). you’ll use the SortedSet category to take care of a group that’s mechanically sorted once new things area unit other.ArrayList capability is the range of components that ArrayList will hold. Once part is other than the ArrayList, reallocation mechanically will increase its capability as required. you’ll scale back the capability by business TrimToSize or by expressly setting the capability property.

    .NET Framework only:

    For terribly massive ArrayList objects, you’ll increase the most capability to two billion components on 64-bit systems by setting the enabled attribute of the element to true within the runtime atmosphere.

    • Items during this assortment are often accessed with an associated whole number index. The index for this assortment is zero-based.
    • The ArrayList assortment accepts null as a sound value. It additionally permits duplicate components.
    • Using four-dimensional arrays as components in the associate ArrayList assortment isn’t supported.

    Conclusion

    A collection could be a category, therefore you need to declare an associate instance of the category before you’ll add components to its assortment. If your assortment contains components of only 1 knowledge kind, you’ll use one among the categories within the System. Collections. Generic namespace. assortment categories serve numerous functions, like allocating memory dynamically to components associated accessing an inventory of things on the idea of an index etc. These categories produce collections of objects of the item category, that is that the base category for all knowledge varieties in C#.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses