A collection is a powerful construct that allows a developer to
logically group related elements and navigate through them. In .NET, a
collection is specifically anything that implements the
ICollection
interface.
As you can see, it really all "starts" with the interface
The popular
As you can see, the concept is similar ... get me to the beginning, get me to the next, and always have a reference to the current.
IEnumerator
. Something that implements this interface can move through the set of items. You can Reset()
to the beginning, take a look at the Current()
object, and get to the next one with MoveNext()
.The popular
for
loop that exists in similar
form in multiple languages really encapsulates the entire interface. A
typical example looks like this:As you can see, the concept is similar ... get me to the beginning, get me to the next, and always have a reference to the current.
Object
class is the base class of every type in .NET. All the collections implement IEnumerable
interface that is extended by ICollection
interface. IDictionary
and IList
are also interfaces for collection which are derived from ICollection
as shown in the diagram. System.Object
Object
class is the base class of every type. All other types directly or indirectly derive from object
class. Because of its lofty position, a .NET developer should have a good knowledge of the object
class and its members. -
Static Methods
-
object.Equals(object objA, object objB)
- This method does some testing for
null
onobjA
andobjB
and callsobjA.Equals(objB)
. It returnstrue
ifobjA
andobjB
arenull
references or both are the same instance, or ifobjA.Equals(objB)
returnstrue
, otherwise it returnsfalse
.
int n1 = 2; int n2 = 3; bool result1 = object.Equals(n1, n2); // returns false. // because n1 & n2 are value type // and it will be compared by value. string s1 = "test"; string s2 = "test"; bool result2 = object.Equals(s1, s2); // returns true. s1 & s2 are // reference type, // but Equals(object obj) method of // object class is overridden by // string class. // that's why it returns true because // s1 and s2 are comparing // by their values. object obj1 = new Person(1, "Test1"); object obj2 = new Person(1, "Test1"); bool result3 = object.Equals(obj1, obj2); // returns false. obj1 & obj2 // are reference type, // both are comparing by // reference and both are // different instances but // having same values.
-
object.ReferenceEquals(object objA, object objB)
This method returnstrue
ifobjA
is the same instance asobjB
or both havenull
reference, otherwise returnfalse
.
int n1 = 2; int n2 = 2; bool result1 = object.ReferenceEquals(n1, n2); // returns false. // because n1 & n2 are // different instances. object obj1 = new Person(1, "Test1"); object obj2 = new Person(1, "Test1"); object obj3 = obj1; bool result2 = object.ReferenceEquals(obj1, obj2); // returns false because // obj1 & obj2 are different instances. bool result3 = object.ReferenceEquals(obj1, obj3); // returns true because // obj1 & obj2 are same instances.
- This method does some testing for
-
Methods
-
Equals(object obj)
The default implementation ofEquals()
supports reference equality only, but derived class can override this method to support value equality. An example isstring
class, which overridesEquals()
to ensure that the two strings are compared by the value of their strings. A common operation, especially for searching or sorting in collections is testing two objects for equality.
string s1 = "Test"; string s2 = "Test"; bool result1 = s1.Equals(s2); // returns true. // because s1 & s2 has same value. object obj1 = new Person(1, "Test1"); object obj2 = new Person(1, "Test1"); object obj3 = obj1; bool result2 = obj1.Equals(obj2); // returns false. // because obj1 & obj2 are different // instances. bool result3 = obj1.Equals(obj3); // returns true. // because obj1 & obj3 are same instances.
-
GetHashCode()
It returns the hash code for the current object. This method also serves as a hash function for a particular type. It is suitable for use in hashing algorithms and data structures like a hash table. This method can be overridden by thederive
class.Object.GetHashCode()
returns the same hash code for the same instance, but it is not necessary that it will return a different hash code for two different instances or the same hash code for two instances which have the same values. Different versions of the .NET Framework might also generate different hash codes for the same instance.
Default hash code returned by theGetHashCode()
method has no guarantee to be unique, you should overrideGetHashCode
in your custom types.
object obj1 = 4; object obj2 = "Test"; object obj3 = new Person(1, "Test1"); int result1 = obj1.GetHashCode(); // returns 4. int result2 = obj2.GetHashCode(); // returns -354185577. int result3 = obj3.GetHashCode(); // returns 2418355.
-
GetType()
It returns theType
object of current instance.Type
is the basis for using reflection in .NET. Use the members ofType
to get information about a type declaration, such as the constructors, methods, fields, properties, and events of a class, as well as the module and the assembly in which the class is deployed.
object obj1 = 4; object obj2 = "Test"; object obj3 = new Person(1, "Test1"); string type1 = obj1.GetType().ToString(); // returns System.Int32 string type2 = obj2.GetType().ToString(); // returns System.String. string type3 = obj3.GetType().ToString(); // returns DotNetCollections. // CollectionExp.Person.
-
ToString()
It returns the human readable string of the object that is culture specific. The default implementation returns the runtime type of the object. The derive class can override this method for returning meaningful value of the type. For example, theToString()
method ofDouble
returns thestring
representation of the value that the object has.
object obj1 = 4; object obj2 = "Test"; object obj3 = new Person(1, "Test1"); string s1 = obj1.ToString(); // returns 4 string s2 = obj2.ToString(); // returns Test string s3 = obj3.ToString(); // returns DotNetCollections. // CollectionExp.Person.
-
System.Collections.IEnumerable
It exposes the enumerator, which provides a collection like behavior to user defined classes.-
Methods
-
GetEnumerator()
It returns the enumerator object that can be used to iterate through the collection. It allows using theforeach
statement. Enumerators only allow reading the data in the collection.
Array array = new int[] { 12, 24, 26, 35, 40, 59 }; IEnumerator iEnum = array.GetEnumerator(); string msg = ""; while (iEnum.MoveNext()) { int n = (int)iEnum.Current; msg += n.ToString() + "\n"; } MessageBox.Show(msg);
-
System.Collections.ICollection
ICollection
interface specifies a method for getting the
size of collection, creating enumerators on a collection and managing
synchronized access to all non-generic collections. It is a base
interface for classes in the System.Collections
namespace. -
Properties
Count
It returns the number of elements contain byICollection
.
// Array List ArrayList sourceList = new ArrayList(); sourceList.Add(10); sourceList.Add(20); sourceList.Add(30); int count = sourceList.Count; // count = 3.
IsSynchronized
It returnstrue
if access to theICollection
is synchronized.
SyncRoot
It returns an object that can be used to synchronize access to theICollection
.
ArrayList sourceList = new ArrayList(); sourceList.Add(10); sourceList.Add(20); sourceList.Add(30); lock (sourceList.SyncRoot) { string list = string.Empty; foreach (object value in sourceList) { if (list.Length > 0) list += ", "; list += value.ToString(); } MessageBox.Show(list); }
-
Methods
-
CopyTo(Array array, int index)
CopyTo()
method copies the elements of theICollection
object to any array, starting at a particularArray
index. If .NET is unable to cast source type to destination, then it throwsArrayTypeMismatchException
exception.
// Copy int array to other int array int[] sourceIDs = new int[] { 1, 2, 3, 4, 5 }; int[] destinationIDs = new int[sourceIDs.Length]; sourceIDs.CopyTo(destinationIDs, 0); // destinationIDs = 1, 2, 3, 4, 5 // Copy array list items to int array. // But each item in array list has int type ArrayList sourceList = new ArrayList(); sourceList.Add(10); sourceList.Add(20); sourceList.Add(30); int[] destinationList = new int[5]; destinationList[0] = 1; destinationList[1] = 5; sourceList.CopyTo(destinationList, 2); // start copy on index 2. // destinationList = 1, 5, 10, 20, 30
-
System.Collections.IList
IList
interface represents the collection of objects that can be individually accessed by index. IList
interface represents the collection of objects that can be individually accessed by index. The implementation of IList
falls into three categories: read-only, fixed-size, and variable-size. A read only IList
cannot be modified. A fixed size IList
does not allow the addition or removal of elements, but it allows the modification of the existing elements. A variables size IList
allows the addition, removal, and modification of elements. -
Properties
IsFixedSize
It returnstrue
ifIList
has fixed size.
ArrayList arrayList = new ArrayList(); bool isFixedSize = arrayList.IsFixedSize; // false, because ArrayList // is not fixed size list
IsReadOnly
It returnstrue
ifIList
is read only.
ArrayList arrayList = new ArrayList(); arrayList.Add(1); arrayList.Add(2); arrayList.Add(3); bool readOnly = arrayList.IsReadOnly; // false, because default array // list is not readonly. // create readonly list from existing list ArrayList readOnlyList = ArrayList.ReadOnly(arrayList); bool isNewListReadOnly = readOnlyList.IsReadOnly; // true. now user can't // modify this list
-
Methods
-
Add(object value)
It adds the item into theIList
.
ArrayList arrayList = new ArrayList(); arrayList.Add(1); // Add First Item arrayList.Add(2); // Add Second Item arrayList.Add(3); // Add Third Item
-
Clear()
It removes the all items from theIList
.
ArrayList arrayList = new ArrayList(); arrayList.Add(1); arrayList.Add(2); arrayList.Add(3); int itemsCount = arrayList.Count; // 3 arrayList.Clear(); itemsCount = arrayList.Count; // 0
-
Contains(object value)
It returnstrue
ifIList
contain a specific value. This method uses theEquals
andCompareTo
methods to determine whether an item exists.
ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1,"test")); Person person1 = new Person(1, "test"); Person person2 = new Person(2, "test2"); bool result1 = arrayList.Contains(person1); // true bool result2 = arrayList.Contains(person2); // false
-
IndexOf(object value)
It returns the index of a specific item in theIList
. This method also uses theEquals
andCompareTo
methods to determine whether an item exists.
// Populate Array list ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); // create new object Person person3 = new Person(3, "test3"); Person person4 = new Person(4, "test4"); int result1 = arrayList.IndexOf(person3); // 2, int result2 = arrayList.IndexOf(person4); // -1. because it does not exist // in list
-
Insert(int index, object value)
It inserts an item to theIList
at specific index. If index equals the number of items in theIList
, then value is appended to the end, but if index greater then the number of items in theIList
or less then zero, then it throwsArgumentOutOfRangeException
exception. If you try to insert item in the read-only or fixed sizeIList
then it throwsNotSupportedException
exception.
ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); // create new object Person person =new Person(4, "test4"); // insert item at index 2. arrayList.Insert(2, person);
-
Remove(object value)
It removes the first occurrence of a specific object from theIList
. If you try to remove value from read only or fixed sizeIList
, then it throwsNotSupportedException
.
ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); // Create person Person person = new Person(2, "test2"); arrayList.Remove(person); // it will remove 2nd item. it will call // Equals method to object to find in list.
-
RemoveAt(int index)
It removes an item at the specified index. It throwsArgumentOutOfRangeException
exception for invalid index in list and throwsNotSupportedException
exception for read only and fixed sizeIList
.
ArrayList arrayList = new ArrayList(); arrayList.Add(new Person(1, "test1")); arrayList.Add(new Person(2, "test2")); arrayList.Add(new Person(3, "test3")); arrayList.RemoveAt(1); // remove item at index 1
-
System.Collections.IDictionary
It represents a collection of key/value pairs.IDictionary
interface is implemented by classes that supports collections of
associated keys and values. Each element in a key/value pair is stored
in a DictionaryEntry
object. It allows the contained keys and values to be enumerated, but it does not imply any particular sort order. -
Properties
IsFixedSize
It returnstrue
ifIDictionary
object has a fixed size.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); bool result = hashList.IsFixedSize; // false
IsReadOnly
It returnstrue
ifIDictionary
object is read only.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); bool result = hashList.IsReadOnly;
Keys
It returnsICollection
object containing keys of theIDictionary
object.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); ICollection keys = hashList.Keys; string[] strKeys = new string[keys.Count]; int index =0; foreach (int key in keys) { strKeys[index++] = key.ToString(); } string keysList = string.Join(", ",strKeys); // 3, 2, 1
Values
It returnsICollection
object containing values of theIDictionary
object.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); ICollection values = hashList.Values; string[] strValues = new string[values.Count]; int index = 0; foreach (string value in values) { strValues[index++] = value; } string valueList = string.Join(", ", strValues); //item#1, item#2, item#3
-
Methods
-
Add(object key, object value)
Adds an element with the specifiedkey
andvalue
into theIDictionary
object.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3");
-
Clear()
It removes all elements from theIDictionary
object.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); hashList.Clear(); // it removes all item from the list.
-
Contains(object key)
It returnstrue
ifIDictionary
object contains an element with the specifiedkey
.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); bool result = hashList.Contains(1); // true
-
GetEnumerator()
It returns anIDictionaryEnumerator
object for theIDictionary
object.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); IDictionaryEnumerator dicEnum = hashList.GetEnumerator(); string items = string.Empty; while (dicEnum.MoveNext()) { items += string.Format("{0} : {1}\n", dicEnum.Key, dicEnum.Value); } MessageBox.Show(items);
-
Remove(object key)
It removes the element with the specifiedkey
from theIDictionary
object.
Hashtable hashList = new Hashtable(); hashList.Add(1, "item#1"); hashList.Add(2, "item#2"); hashList.Add(3, "item#3"); hashList.Remove(2); // remove item which has 2 key
*********************************************************************************
Collection classes are specialized classes for data storage and
retrieval. These classes provide support for stacks, queues, lists, and
hash tables. Most collection classes implement the same interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.
Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.
Various Collection Classes and Their Usage
The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their detail.Class | Description and Useage |
---|---|
ArrayList | It represents ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list. |
Hashtable | It uses a key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection. |
SortedList | It uses a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key , it is a Hashtable. The collection of items is always sorted by the key value. |
Stack | It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. |
Queue | It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is called deque. |
BitArray | It represents an array of the binary representation using the values 1 and 0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero. |
No comments:
Post a Comment