C#- Collection

We had posted about  array before. however C# also includes specialized classes that hold many values or objects in a specific series, that are called ‘collection’.
There are two types of collections available in C#: non-generic collections and generic collections.and now we are going to learn about non-generic collections

Every collection class implements the IEnumerable interface so values from the collection can be accessed using a foreach loop.

The System.Collections namespace includes following non-generic collections.

Non-generic Collections Usage
ArrayList ArrayList stores objects of any type like an array. However, there is no need to specify the size of the ArrayList like with an array as it grows automatically.
SortedList SortedList stores key and value pairs. It automatically arranges elements in ascending order of key by default. C# includes both, generic and non-generic SortedList collection.
Stack Stack stores the values in LIFO style (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values. C# includes both, generic and non-generic Stack.
Queue Queue stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection. C# includes generic and non-generic Queue.
Hashtable Hashtable stores key and value pairs. It retrieves the values by comparing the hash value of the keys.
BitArray BitArray manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).

we will take the above one by one and learn more about them in the next couple of blog posts :).

Please follow and like us:

C# – Array

An array is a special type of data type which can store fixed number of values sequentially using special syntax.

The following image shows how an array stores values sequentially.


 

As you can see in the above figure, index is a number starting from 0, which stores the value. You can store a fixed number of values in an array. Array index will be increased by 1 sequentially till the maximum specified array size.

Array Declaration

An array can be declare using a type name followed by square brackets [].

Example: Array declaration in C#
int[] intArray; // can store int values
bool[] boolArray; // can store boolean values

string[] stringArray; // can store string values

double[] doubleArray; // can store double values
byte[] byteArray; // can store byte values
Courses[] customClassArray; // can store instances of Courses class

Initialization

An array can be declared and initialized at the same time using the new keyword. The following example shows the way of initializing an array.

Example: Array Declaration & Initialization
// defining array with size 5. add values later on
int[] intArraySample1 = new int[5]; 
// defining array with size 5 and adding values at the same time
int[] intArraySample2 = new int[5]{1, 2, 3, 4, 5};
// defining array with 5 elements which indicates the size of an array
int[] intArraySample3 = {1, 2, 3, 4, 5};

In the above example, the first statement declares & initializes int type array that can store five int values. The size of the array is specified in square brackets. The second statement, does the same thing, but it also assignes values to each indexes in curley brackets { }. The third statement directly initializes an int array with the values without giving any size. Here, size of an array will automatically be number of values.

Initialization without giving size is NOT valid. For example, the following example would give compile time error.

Example: Wrong way of initializing an array
int[] intArray = new int[]; // compiler error: must give size of an array

Late initialization

Arrays can be initialized after declaration. It is not necessary to declare and initialize at the same time using new keyword. Consider the following example.

Example: Late initialization of an Array
string[] strArray1, strArray2;

strArray1 = new string[5]{ "1st Element",
                           "2nd Element", 
                           "3rd Element",
                           "4th Element",
                           "5th Element" 
                          };


strArray2 = new string[]{ "1st Element",
                           "2nd Element",
                           "3rd Element",
                           "4th Element", 
                           "5th Element" 
                          };

However, in the case of late initialization, it must be initialized with the new keyword as above. It cannot be initialize by only assigning values to the array.

The following initialization is NOT valid:

Example: Wrong way of initializing an array
string[] strArray;

strArray = {"1st Element","2nd Element","3rd Element","4th Element" };

Accessing Array Elements

As shown above, values can be assigned to an array at the time of initialization. However, value can also be assigned to individual index randomly as shown below.

Example: Assigning values to array index
int[] intArray = new int[5];
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;

In the same way, you can retrieve values at a particular index, as below:

Example: Accessing Array elements

intArray[0];  //returns 10
intArray[2];  //returns 30

Use a for loop to access the values from all the indexes of an array by using length property of an array.

Example: Accessing Array elements using for loop
int[] intArray = new int[5]{10, 20, 30, 40, 50 };

for(int i = 0; i < intArray.Length; i++)
    Console.WriteLine(intArray[i]);   
10 
20
30
40
50

Array properties and methods

Method Name Description
GetLength(int dimension) Returns the number of elements in the specified dimension.
GetLowerBound(int dimension) Returns the lowest index of the specified dimension.
GetUpperBound(int dimension) Returns the highest index of the specified dimension.
GetValue(int index) Returns the value at the specified index.
Property Description
Length Returns the total number of elements in the array.

Array Helper Class

.NET provides an abstract class, Array, as a base class for all arrays. It provides static methods for creating, manipulating, searching, and sorting arrays.

For example, use the Array.Sort() method to sort the values:

Example: Array Helper class
int[] intArr = new int[5]{ 2, 4, 1, 3, 5};

Array.Sort(intArr);

Array.Reverse(intArr);

You can create an instance of an Array that starts with index 1 (not default starting index 0) using Array class as shown below:

Example: Array Helper class
Array array = Array.CreateInstance(typeof(int),new int[1]{5},new int[1]{1});

array.SetValue(1, 1);
array.SetValue(2, 2);
array.SetValue(3, 3);
array.SetValue(4, 4);
array.SetValue(5, 5);

for (int i = 1; i <= array.Length; i++)
    Console.WriteLine("Array value {0} at position {1}", array.GetValue(i), i);
Output:

Array value 1 at position 1
Array value 2 at position 2
Array value 3 at position 3
Array value 4 at position 4
Array value 5 at position 5

 never forget  :
  1. An Array stores values in a series starting with a zero-based index.
  2. The size of an array must be specified while initialization.
  3. An Array values can be accessed using indexer.
  4. An Array can be single dimensional, multi-dimensional and jagged array.
  5. The Array helper class includes utility methods for arrays.
Please follow and like us:

Basic Operation’s That SharePointer Needs For SharePointing By Using CSOM – Part 3

Previously in part one we discussed the main operation that developers needs to deal with SharePoint site , and in part 2 , we talked about  SharePoint list , and the bellow examples show how to use the .NET Framework CSOM to complete list item -related tasks.

SharePoint list item tasks

These examples demonstrate how to use the .NET Framework CSOM (Client side object model) to complete tasks that are related to list items.

Retrieve items from a SharePoint list

This example retrieves the items in a SharePoint list. You also need to add a using statement for Microsoft.SharePoint.Client.QueryExpression.

Note

You can use the FolderServerRelativeUrl property to further restrict the items that are returned to those in a specified folder.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll" 
// so that it grabs all list items, regardless of the folder they are in. 
CamlQuery query = CamlQuery.CreateAllItemsQuery(100); 
ListItemCollection items = announcementsList.GetItems(query); 

// Retrieve all items in the ListItemCollection from List.GetItems(Query). 
context.Load(items); 
context.ExecuteQuery(); 
foreach (ListItem listItem in items) 
{ 
    // We have all the list item data. For example, Title. 
    label1.Text = label1.Text + ", " + listItem["Title"]; 
} 

Create a new list item

This example creates a new SharePoint list item by using the ListItemCreationInformation class.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// We are just creating a regular list item, so we don't need to 
// set any properties. If we wanted to create a new folder, for 
// example, we would have to set properties such as 
// UnderlyingObjectType to FileSystemObjectType.Folder. 
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 
ListItem newItem = announcementsList.AddItem(itemCreateInfo); 
newItem["Title"] = "New Item!"; 
newItem["Body"] = "Hello Developers world!"; 
newItem.Update(); 

context.ExecuteQuery();  

Update a list item

This example updates a SharePoint list item.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.GetItemById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery();  

Delete a list item

This example deletes a SharePoint list item.

C#
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://developersportal.net"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume that there is a list item with ID=2. 
ListItem listItem = announcementsList.GetItemById(2); 
listItem.DeleteObject(); 

context.ExecuteQuery(); } 
Please follow and like us: