arr.Add("Item1");
arr.Insert(3, "Item3");
arr.Remove("item2")
ItemList.RemoveAt(2)
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:
ArrayList:
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:
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.
ArrayListObject.Add(element);
For example:
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.
Senthil kumar 1 2 3 4
Clear:
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.
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.
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.
ArrayListObject.Insert(Position,Object);
134
oArrayList.Insert(2,2);
1234
InsertRange:
ArrayListObject.InsertRange(Position,CollectionObject);
If you check the output of the ArrayList will be like the following.
156
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.
RemoveAt:
The RemoveAt method is used to delete the specified location element in the
ArrayList.
ArrayListObject.RemoveAt(ArrayListIndex);
RemoveRange:
oArrayList.RemoveAt(5,3);
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();
oArrayList.Add("B");
oArrayList.Add("A");
oArrayList.Add("Z");
oArrayList.Sort();
ABZ
Reverse:
The Reverse method is used to arrange the objects in the Reverse order.
ArrayListObject.Reverse();
oArrayList.Add("A");
oArrayList.Add("B");
oArrayList.Add("C");
oArrayList.Reverse();
ABC
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.
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")
Advantages:
Disadvantages:
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.
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:
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;
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.
// keyword_enum.cs
// enum initialization:
using System;
public class EnumTest
{
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
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:
}
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);
}
• 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
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
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];
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
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"};
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"} };
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"} };
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 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;
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;
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;
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);
}
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