Anda di halaman 1dari 19

ArrayList is one of the most flexible data structure from CSharp Collections.

ArrayList contains a simple list of values. ArrayList implements the IList


interface using an array and very easily we can add , insert , delete , view etc. It
is very flexible because we can add without any size information , that is it will
grow dynamically and also shrink .
Add : Add an Item in an ArrayList
Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remove an item from a specified position

Sort : Sort Items in an ArrayList

How to add an Item in an ArrayList ?


Syntax : ArrayList.add(object)
object : The Item to be add the ArrayList
ArrayList arr;

arr.Add("Item1");

How to Insert an Item in an ArrayList ?


Syntax : ArrayList.insert(index,object)
index : The position of the item in an ArrayList
object : The Item to be add the ArrayList
ArrayList arr;

arr.Insert(3, "Item3");

How to remove an item from arrayList ?


Syntax : ArrayList.Remove(object)
object : The Item to be add the ArrayList

arr.Remove("item2")

How to remove an item in a specified position from an ArrayList ?


Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList

ItemList.RemoveAt(2)

How to sort ArrayList ?


Syntax : ArrayList.Sort()

Introduction:
Mirosoft.Net has the many namespaces for different purpose s. Among that
System.Collections is very important namespace in the programmers
perceptive. During the coding, we look some classes that need to reduce the
manual operation. For instance if you want to sort the values in the array
then you have to do the manual operations. Here obviously we look the
classes that can automate the sorting in just calling a method. In other words
we can call this namespace as utility namespace. Let us see the classes in
this namespace.

Collection Classes:

The System.Collections namespace has many classes for the individual


purpose. We are going to discuss the frequently used classes in this article.

• <!--[if !supportLists]--> <!--[endif]-->ArrayList


• <!--[if !supportLists]--> <!--[endif]-->BitArray
• <!--[if !supportLists]--> <!--[endif]-->Stack
• <!--[if !supportLists]--> <!--[endif]-->Queue
• <!--[if !supportLists]--> <!--[endif]-->Comparer
• <!--[if !supportLists]--> <!--[endif]-->HashTable
• <!--[if !supportLists]--> <!--[endif]-->SortedList

ArrayList:

The ArrayList is one of the important classes in the System.Collection namespace.


We can say it is the next generation of the Array in C#.

ArrayList is a dynamical array; it will increase the size of the storage location as
required. It stores the value as object. The allocation of the ArrayList can be
achieved through the TrimToSize property.

Methods:

1 Add It will add the element as object in the ArrayList


2 AddRange It will add the collections of elements in the object as individual objects in
the ArrayList
3 Clear It will clear the all objects in the ArrayList
4 BinarySearch It will return the position of the search object as integer value.
5 Insert It will insert the element in the specified location of the index in the
ArrayList.
6 InsertRange It will insert the elements in the object as individual objects in the
specified location.
7 Remove It will remove the given object in the first occurrence in the ArrayList.
8 RemoveAt It will remove the object as specified in the argument.
9 RemoveRange It will remove the set of objects in the ArrayList from the range specified.
10 Sort It will do the sorting of the elements in the ascending order.
11 Reverse It will arrange the elements in the reverse order in the ArrayList.
12 GetEnumerator It will return the collection of objects in the ArrayList as enumerator.
13 Contains It checks whether the objects exists or not.

Add:

This Add method is used to add an object to the ArrayList. Whatever we add
element to the ArrayList then it consider as an object.

Let us see how to add element into ArrayList.

ArrayListObject.Add(element);

For example:

ArrayList oArrayList = new ArrayList();


oArrayList.Add("senthil");
oArrayList.Add("Kumar");
oArrayList.Add(99);
oArrayList.Add("@");
oArrayList.Add("55.55");
oArrayList.Add(oStack);

Here, I have added few elements that everything considers as an object. Elements
can be duplicate or you can add null into the ArrayList. The size will be expanded
when you insert new elements.

Add Range:

The Add range method will be add the elements in the other collections. Here
the elements can be null, but the Add range collection cannot be null.

Consider this example for better understanding.

Stack oStack = new Stack();


oStack.Push(1);
oStack.Push(2);
oStack.Push(3);
oStack.Push(4);

ArrayList oArrayList = new ArrayList();


oArrayList.Add("Senthil");
oArrayList.Add("Kumar");
oArrayList.AddRange(oStack);
Here what happens, when you add the Stack object it considers as one of the
element in the ArrayList. But when you use AddRange method it stores the elements
in the Stack as individual elements in the ArrayList.
It adds the elements at the end of the ArrayList.

Here the output will be like the following.

Senthil kumar 1 2 3 4

Clear:

Clear method is used to clear the elements in the ArrayList.

ArrayListObject.Clear();
ArrayList oArrayList = new ArrayList();
oArrayList.Add("c#");
oArrayList.Add("Java");
oArrayList.Add("PHP");

If you see the total elements in the ArrayList will be 3. You can check with the
Count property.

Here I clear the ArrayList.

oArrayList.Clear();

Now count of the ArrayList is 0. However the Capacity remains the same as
set.

BinarySearch:

The BinarySearch method is used to get the location of the object in the
ArrayList.

It uses the Binary search algorithm to find the elements. It will return the
element position in the ArrayList. Here the object can be duplicate, in that
case it will return the any one occurrences position of the element.

Consider the following example,

ArrayList oArrayList = new ArrayList();


oArrayList.Add(1);
oArrayList.Add(3);
oArrayList.Add(5);
oArrayList.Add(7);
int iPos = oArrayList.BinarySearch(3);
Here it will return the location of the index value into the integer variable.

Insert:

The Insert method is used to insert the new element in the existing ArrayList.
This is new specific feature in the ArrayList when you compare with the Array.
Here it uses the LinkedList, when you insert the element then it will move the
node.

The syntax of the Insert method is following.

ArrayListObject.Insert(Position,Object);

Consider this example for the better understanding.

ArrayList oArrayList = new ArrayList();


oArrayList.Add(1);
oArrayList.Add(3);
oArrayList.Add(4);

If you check the ArrayList, elements will be stored like this.

134

Let us insert a new element in the position of 2.

oArrayList.Insert(2,2);

Now we have inserted the element in the ArrayList.

After insertion, the output will be like the following.

1234

InsertRange:

InsertRange method is used to insert the collection of the elements in the


other collections from the specified index position. Here it will insert the
individual object from the collection object.

ArrayListObject.InsertRange(Position,CollectionObject);

Let us see with an example.

ArrayList oArrayList = new ArrayList();


oArrayList.Add(1);
oArrayList.Add(5);
oArrayList.Add(6);

If you check the output of the ArrayList will be like the following.
156

Now I am going to insert the collection object.

Stack oStack = new Stack();


oStack.Push(2);
oStack.Push(3);
oStack.Push(4);
oArrayList.InsertRange(2,oStack);

We have inserted the range of elements from the Stack.

Now output of the ArrayList will be like the following.

123456

Remove:

The Remove method is used to remove the element from the ArrayList. If
there are multiple objects in the same name when you try to remove,, then it
will remove the first occurrences in the ArrayList. In case of no elements
found then it will not thrown any exception and ArrayList count remains
same.

The syntax of the Remove method as given below.

ArrayList oArrayList = new ArrayList();


oArrayList.Add("Senthil");
oArrayList.Add("Kumar");
oArrayList.Add("Senthil");
oArrayList.Remove("Senthil");

Here it will remove the first element in the ArrayList.

RemoveAt:

The RemoveAt method is used to delete the specified location element in the
ArrayList.

The syntax of the RemoveAt method is given below.

ArrayListObject.RemoveAt(ArrayListIndex);

Let us see an example,

ArrayList oArrayList = new ArrayList();


oArrayList.Add("Senthil");
oArrayList.Add("Kumar");
oArrayList.Add("Senthil");
oArrayList.RemoveAt(1);
Here the second element will be removed from the ArrayList.

RemoveRange:

The RemoveRange method is used to remove the collection of objects in the


ArrayList.

It removes the range of Starting position to number of elements specified in


the RemoveRange method.

ArrayListObject.RemoveRange(Starting Index, Number of objects);

Let us see an example for better understanding.

ArrayList oArrayList = new ArrayList();


For(int i=1;i<10;i++)
{
oArrayList.Add(i);
}

Here 10 elements will be added as object in the Array List.

I am going to delete 3 elements starts from 5.

oArrayList.RemoveAt(5,3);

Now the output will be like the following.

1 2 3 4 8 9 10

Sort:

The Sort method is used to sort the objects in the ascending order. It uses the
QuickSort algorithm to sort the elements in the ArrayList.

ArrayListObject.Sort();

Let us see an example.

oArrayList.Add("B");
oArrayList.Add("A");
oArrayList.Add("Z");
oArrayList.Sort();

The output of the above ArrayList will be like this.

ABZ

Reverse:
The Reverse method is used to arrange the objects in the Reverse order.

ArrayListObject.Reverse();

Let us see an example.

oArrayList.Add("A");
oArrayList.Add("B");
oArrayList.Add("C");
oArrayList.Reverse();

Before the reverse method

ABC

After the revserse method

CBA

GetEnumerator:

The GetEnumerator method is used to get the collection of the objects in the
ArrayList as Iterator. This can be implemented with suitable interface.
Howevery the ArrayList elements can be iterated through the foreach or loop
statements.

Let us consider the following example code snippet.

oArrayList.Add("B");
oArrayList.Add("A");
oArrayList.Add("Z");
IEnumerator OIEnum = oArrayList.GetEnumerator();

Contains:

This method is used to check whether the element exists or not. It returns the
Boolean result.

OArrayList.Contains("Senthil")

Properties in the ArrayList

S.No Property Name Description


1 Capcity This property is used to set or get the size to the
ArrayList.
As you know it will increase the size of the storage as
much as required. Default size will be 16.
2 Count It returns the total number of elements in the
ArrayList.
3 IsFixedSize It returns the Whether the ArrayList is fixed size or
not. It returns the Boolean value.
4 IsReadOnly It returns the Whether the ArrayList is Readyonly or
not. It returns the Boolean value.

Advantages:

• <!--[if !supportLists]--> <!--[endif]-->The ArrayList is not a specific data type


storage location, it stores everything as object.
• <!--[if !supportLists]--> <!--[endif]-->No need to do allocation and
deallocation explicitly to store the data.
• <!--[if !supportLists]--> <!--[endif]-->It has the explicit sorting methods.
• <!--[if !supportLists]--> <!--[endif]-->It can insert and delete the elements in
between positions in the ArrayList.
• <!--[if !supportLists]--> <!--[endif]-->It can store the object as elements.

Disadvantages:

• <!--[if !supportLists]--> <!--[endif]-->ArrayList is not a strongly typed one. It


has to do the type casting when you retrieve the content. When we do the
type casting every time, it hits the performance.
• <!--[if !supportLists]--><!--[endif]-->It uses the LinkedList storage
approach, because if you insert or delete the specific position it has to
forward/backward in the storage address.
• <!--[if !supportLists]--><!--[endif]-->Sometimes it leads to the runtime
error. Consider an example, we store the ids of the employee in the arraylist
and then we want to retrieve the element for some other operations.
Obviously we need to do the type casting, that time if there is any string
element then what will happen? It will throw the error.

Difference between Array and ArrayList

Array ArrayList
Array uses the Vector array to store ArrayList uses the LinkedList to store
the elements the elements.
Size of the Array must be defined No need to specify the storage size.
until redim used( vb)
Array is a specific data type storage ArrayList can be stored everything as
object.
No need to do the type casting Every time type casting has to do.
It will not lead to Runtime It leads to the Run time error
exception exception.
Element cannot be inserted or Elements can be inserted and deleted.
deleted in between.
There is no built in members to do ArrayList has many methods to do
ascending or descending. operation like Sort, Insert, Remove,
BinarySeacrh,etc..,
Conclusion:

So far we have seen the ArrayList and its members and properties. I hope
that this has given enough practical idea about the ArrayList. Next we are
going to discuss about the BitArray in the same collection class. If you have
any query or further clarifications about this ArrayList please free to post your
feedback and corrections.

The enum keyword is used to declare an enumeration, a distinct type consisting of a


set of named constants called the enumerator list. Every enumeration type has an
underlying type, which can be any integral type except char. The default underlying
type of the enumeration elements is int. By default, the first enumerator has the
value 0, and the value of each successive enumerator is increased by 1. For
example:

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have
initializers to override the default values. For example:

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

In this enumeration, the sequence of elements is forced to start from 1 instead of 0.

A variable of type Days can be assigned any value in the range of the underlying
type; the values are not limited to the named constants.

The default value of an enum E is the value produced by the expression (E)0.

The underlying type specifies how much storage is allocated for each enumerator.
However, an explicit cast is needed to convert from enum type to an integral type.
For example, the following statement assigns the enumerator Sun to a variable of the
type int using a cast to convert from enum to int:

int x = (int)Days.Sun;

When you apply System.FlagsAttribute to an enumeration that contains some


elements combined with a bitwise OR operation, you will notice that the attribute
affects the behavior of the enum when used with some tools. You can notice these
changes when using tools such as the Console class methods, the Expression
Evaluator, and so forth. (See example 3).

Assigning additional values new versions of enums, or changing the values of the
enum members in a new version, can cause problems for dependant source code. It
is often the case that enum values are used in switch statements, and if additional
elements have been added to the enum type, the test for default values can return
true unexpectedly.

If other developers will be using your code, it is important to provide guidelines on


how their code should react if new elements are added to any enum types.

In this example, an enumeration, Days, is declared. Two enumerators are explicitly


converted to integer and assigned to integer variables.

// keyword_enum.cs
// enum initialization:
using System;
public class EnumTest
{
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

static void Main()


{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}

Output

Sun = 2
Fri = 7

In this example, the base-type option is used to declare an enum whose members
are of the type long. Notice that even though the underlying type of the
enumeration is long, the enumeration members must still be explicitly converted to
type long using a cast.

// keyword_enum2.cs
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}

Output

Max = 2147483648
Min = 255

The following code example illustrates the use and effect of the
System.FlagsAttribute attribute on an enum declaration.

// enumFlags.cs
// Using the FlagsAttribute on enumerations.
using System;

[Flags]
public enum CarOptions
{
SunRoof = 0x01,
Spoiler = 0x02,
FogLights = 0x04,
TintedWindows = 0x08,
}

class FlagTest
{
static void Main()
{
CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
Console.WriteLine(options);
Console.WriteLine((int)options);
}
}

Output

SunRoof, FogLights
5

Comments

Notice that if you remove the initializer from Sat=1, the result will be:

Sun = 1
Fri = 6

Comments

Notice that if you remove FlagsAttribute, the example will output the following:

Difference between string and string Builder

String and String Builder class shows resemblance in terms


of values they accept(that contain series of haracters).But
the thing that distinguishes them is that string is
immutable .Immutable in the sense it will create a new copy
of memory whenever a new string is concatenated to the
existing string variable That means the existing memory is
deleted and replaced by the new memory.Whereas
Stringbuilder is mutable whenever we append a new string to
the existing string variable using append method the memory
containing the original string is extended to contain the
new string as well i.e, it won`t replace it with new memory
allocation.Hence performing string concatenations within
the same variable in the string class variables will affect
their performance.
2)
String bulider Can Be Used When More Than One String Can we
concatenated.
StringBuilder which is more efficient because it does
contain a mutable string buffer. .NET Strings are immutable
which is the reason why a new string object is created
every time we alter it (insert, append, remove, etc.).

StringBulider Is more Effiecent Then String B'Cuse It


Provide Some Standered Function like Append,Reverse,Remove
etc.
what is the difference between arraylist and hash table using a simple program?

1)In Array We Can Add any datatype value,Every item in


arraylist is treated as object.
2)Hashtable is collection of key,value pairs
i)Key Can be any datatype
ii)Key Cannot be null refrrence
iii)but value can be null referrence

Retrieving by key in Hashtable is faster than retrieving in


Arraylist,
Example of Arraylist:
Arraylist ar = new Arraylist();
ar.add("X");
ar.add(1);
ar.add(2);
Now if we Retrieve from Arraylist like
foreach(string str in ar)
{

}
It will Compile but it will give Runtime
Error,because '1' and '2' in Arraylist are integers.

Example Hashtable:
Hashtable ht = new Hashtable();
ht.add(1,"sample");
ht.add("2","Test");
ht.add(3,4);
foreach(Dictionaryentry dr in ht.keys.values)
{
Console.Writeline(dr.keys + "=" + dr.values);
}

The Above Code wont give any runtime Error Because We


are iterating through DictionaryEntries(Hashtable
implements IDictionary) it is Collection of Key/Value Pairs
This tutorial is divided into the following sections:

• Arrays in General
• Declaring Arrays
• Initializing Arrays
• Accessing Array Members
• Arrays are Objects
• Using foreach with Arrays

Arrays in General

C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C#
work similarly to how arrays work in most other popular languages There are,
however, a few differences that you should be aware of.

When declaring an array, the square brackets ([]) must come after the type, not the
identifier. Placing the brackets after the identifier is not legal syntax in C#.

Copy
int[] table; // not int table[];

Another detail is that the size of the array is not part of its type as it is in the C
language. This allows you to declare an array and assign any array of int objects to
it, regardless of the array's length.

Copy
int[] numbers; // declare numbers as an int array of any size
numbers = new int[10]; // numbers is a 10-element array
numbers = new int[20]; // now it's a 20-element array

Declaring Arrays

C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays),


and array-of-arrays (jagged arrays). The following examples show how to declare
different kinds of arrays:

Single-dimensional arrays:

Copy
int[] numbers;

Multidimensional arrays:

Copy
string[,] names;

Array-of-arrays (jagged):

Copy
byte[][] scores;

Declaring them (as shown above) does not actually create the arrays. In C#, arrays
are objects (discussed later in this tutorial) and must be instantiated. The following
examples show how to create arrays:

Single-dimensional arrays:

Copy
int[] numbers = new int[5];

Multidimensional arrays:

Copy
string[,] names = new string[5,4];

Array-of-arrays (jagged):

Copy
byte[][] scores = new byte[5][];
for (int x = 0; x < scores.Length; x++)
{
scores[x] = new byte[4];
}

You can also have larger arrays. For example, you can have a three-dimensional
rectangular array:

Copy
int[,,] buttons = new int[4,5,3];

You can even mix rectangular and jagged arrays. For example, the following code
declares a single-dimensional array of three-dimensional arrays of two-dimensional
arrays of type int:

Copy
int[][,,][,] numbers;

Example

The following is a complete C# program that declares and instantiates arrays as


discussed above.

Copy
// arrays.cs
using System;
class DeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];

// Multidimensional array
string[,] names = new string[5,4];

// Array-of-arrays (jagged array)


byte[][] scores = new byte[5][];

// Create the jagged array


for (int i = 0; i < scores.Length; i++)
{
scores[i] = new byte[i+3];
}

// Print length of each row


for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
}
}
}

Output

Copy
Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7

Initializing Arrays

C# provides simple and straightforward ways to initialize arrays at declaration time


by enclosing the initial values in curly braces ({}). The following examples show
different ways to initialize different kinds of arrays.

Note If you do not initialize an array at the time of declaration, the array members
are automatically initialized to the default initial value for the array type. Also, if you
declare the array as a field of a type, it will be set to the default value null when you
instantiate the type.

Single-Dimensional Array

Copy
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"};

You can omit the size of the array, like this:

Copy
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};

You can also omit the newoperator if an initializer is provided, like this:

Copy
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Matt", "Joanne", "Robert"};

Multidimensional Array

Copy
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };

You can omit the size of the array, like this:

Copy
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };

You can also omit the newoperator if an initializer is provided, like this:

Copy
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };

Jagged Array (Array-of-Arrays)

You can initialize jagged arrays like this example:

Copy
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

You can also omit the size of the first array, like this:

Copy
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

-or-

Copy
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

Notice that there is no initialization syntax for the elements of a jagged array.

Accessing Array Members

Accessing array members is straightforward and similar to how you access array
members in C/C++. For example, the following code creates an array called numbers
and then assigns a 5 to the fifth element of the array:
Copy
int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;

The following code declares a multidimensional array and assigns 5 to the member
located at [1, 1]:

Copy
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;

The following is a declaration of a single-dimension jagged array that contains two


elements. The first element is an array of two integers, and the second is an array of
three integers:

Copy
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}
};

The following statements assign 58 to the first element of the first array and 667 to
the second element of the second array:

Copy
numbers[0][0] = 58;
numbers[1][1] = 667;

Arrays are Objects

In C#, arrays are actually objects. System.Array is the abstract base type of all
array types. You can use the properties, and other class members, that
System.Array has. An example of this would be using the Lengthproperty to get the
length of an array. The following code assigns the length of the numbers array, which
is 5, to a variable called LengthOfNumbers:

Copy
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;

The System.Array class provides many other useful methods/properties, such as


methods for sorting, searching, and copying arrays.

Using foreach on Arrays

C# also provides the foreach statement. This statement provides a simple, clean
way to iterate through the elements of an array. For example, the following code
creates an array called numbers and iterates through it with the foreach statement:

Copy
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}

With multidimensional arrays, you can use the same method to iterate through the
elements, for example:

Copy
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
Console.Write("{0} ", i);
}

The output of this example is:

Copy
9 99 3 33 5 55

However, with multidimensional arrays, using a nested for loop gives you more
control over the array elements.

See Also

Anda mungkin juga menyukai