c# - How to convert a Stack to an Array


Convert a Stack to an Array



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we convert a Stack instance to an Array instance. That means we will copy a Stack to a new Array. In this .net c# tutorial code, we used the Stack class ToArray() method to create an Array instance from a Stack object.




The Stack class ToArray() method copy the Stack to a new array. This method returns a new array containing copies of the elements of the Stack. The elements are copied onto the array in last-in-first-out order. That is similar to the order of the elements returned by a succession of calls to Pop.



StackToArrayMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("DarkRed");
colors.Push("DarkGreen");
colors.Push("DarkBlue");
colors.Push("DarkSalmon");
colors.Push("DarkViolet");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=DarkViolet>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

var colorsArray = colors.ToArray();

Label1.Text += "<br /><br />After Call Stack.ToArray() method";
Label1.Text += "<br />Array Elements...";
Label1.Text += "<font color=DarkViolet>";
for (int i = 0; i < colorsArray.Length; i++)
{
Label1.Text += "<br />" + colorsArray[i].ToString();
}
Label1.Text += "</font>";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Stack ToArray() Method - How to copy the Stack to a new array</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack ToArray() Method
<br /> How to copy the Stack to a new array
</h2>
<hr width="400" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="DarkGreen"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack ToArray() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to insert an object at the top of the Stack


Insert an object at the top of the Stack



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we insert an object at the top of the Stack. In this .net c# tutorial code, we used the Stack class Push() method to insert an object at the top of a Stack.




The Stack class Push(Object) method inserts an object at the top of the Stack. The Stack class Push(object? obj) method has a parameter named obj. The obj parameter is the Object to push onto the Stack. The value can be null.




StackPushMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("Blue");
colors.Push("DodgerBlue");
colors.Push("SkyBlue");
colors.Push("LightBlue");
colors.Push("DeepSkyBlue");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=DarkOrchid>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

colors.Push("MidnightBlue");

Label1.Text += "<br /><br />After inserting an object at the top of the Stack";
Label1.Text += "<br />using Push(object) method. Now Stack Elements...<br />";
Label1.Text += "<font color=DarkOrchid>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Stack Push() Method - How to insert an object at the top of the Stack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack Push() Method
<br /> How to insert an object at the top of the Stack
</h2>
<hr width="475" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="DarkOliveGreen"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack Push() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - Remove and get the object at the top of the stack


Remove and get the object at the top of the Stack



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we can remove and get the object at the top of the Stack instance. That means we will remove the object and get the object at the top of the Stack at the same time. In this .net c# tutorial code, we used the Stack class Pop() method to remove and get the object at the top of a Stack.




The Stack class Pop() method removes and returns the object at the top of the Stack. The Pop() method returns the Object removed from the top of the Stack. The Stack class Pop() method throws InvalidOperationException if the Stack is empty. The Pop() method is similar to the Peek method, but Peek does not modify the Stack.



StackPopMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("Orange");
colors.Push("DarkOrange");
colors.Push("OrangeRed");
colors.Push("Salmon");
colors.Push("DarkSalmon");
colors.Push("LightSalmon");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=DodgerBlue>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

Label1.Text += "<br /><br />Remove and get the object at the top of the Stack";
Label1.Text += "<br />using Pop() method.... <br />";
Label1.Text += "<font color=DarkBlue>";
Label1.Text += colors.Pop().ToString();
Label1.Text += "</font>";

Label1.Text += "<br /><br />After Call Pop() Method, Now Stack Elements... ";
Label1.Text += "<font color=DeepSkyBlue>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Stack Pop() Method - How to remove and get the object at the top of the Stack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack Pop() Method
<br /> How to remove and get the object at the top of the Stack
</h2>
<hr width="600" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="Tomato"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack Pop() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to get the object at the top of the stack


Get the object at the top of the Stack



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we can get the object at the top of the Stack instance. That means we will only get the object at the top of the Stack without removing it from the Stack. In this .net c# tutorial code, we used the Stack class Peek() method to get the object at the top of a Stack without removing/deleting the object from the Stack.




The Stack class Peek() method returns the object at the top of the Stack without removing it. The Stack Peek() method returns the Object at the top of the Stack. This method throws InvalidOperationException if the Stack is empty. The Stack class Peek() method is similar to the Pop() method, but Peek() method does not modify the Stack.




StackPeekMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("Green");
colors.Push("SeaGreen");
colors.Push("MediumSeaGreen");
colors.Push("DarkGreen");
colors.Push("LawnGreen");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=SlateBlue>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

Label1.Text += "<br /><br />Get the object at the top of the Stack";
Label1.Text += "<br />without removing it using Peek() method.... <br />";
Label1.Text += "<font color=SlateBlue>";
Label1.Text += colors.Peek().ToString();
Label1.Text += "</font>";

Label1.Text += "<br /><br />After Call Peek() Method, Now Stack Elements... ";
Label1.Text += "<font color=SlateBlue>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Stack Peek() Method - How to get the object at the top of the Stack without removing it</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack Peek() Method
<br /> How to get the object at the top of the Stack without removing it
</h2>
<hr width="625" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="MediumVioletRed"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack Peek() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to copy a Stack to an Array


Copy a Stack to an Array




The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we can copy a Stack to an Array. That means we will copy a Stack instance to an Array, starting at the specified starting index of the Array instance. In this .net c# tutorial code, we used the Stack class CopyTo() method to copy Stack items to an Array object.




The Stack class CopyTo(Array, Int32) method copies the Stack to an existing one-dimensional Array, starting at the specified array index. The Stack class CopyTo(Array array, int index) method has two parameters. The array parameter is the one-dimensional Array that is the destination of the elements copied from the Stack. The Array must have zero-based indexing. And the index parameter is the zero-based index in the array at which copying begins.




The Stack class CopyTo(Array array, int index) method throws ArgumentNullException if the array is null. It throws ArgumentOutOfRangeException if the index is less than zero. It also throws InvalidCastException if the type of the source Stack cannot be cast automatically to the type of the destination array.




StackCopyToMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("Red");
colors.Push("DarkRed");
colors.Push("IndianRed");
colors.Push("MediumVioletRed");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=SlateBlue>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

string[] redColors = new string[colors.Count];
colors.CopyTo(redColors,0);

Label1.Text += "<br /><br />After Call CopyTo(array, index 0) Method, Array Elements...";
Label1.Text += "<font color=SlateBlue>";
for(int i=0; i<redColors.Length; i++)
{
Label1.Text += "<br />" + redColors[i].ToString();
}
Label1.Text += "</font>";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to copy Stack to an existing one-dimensional Array, starting at the specified array index</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack CopyTo() Method
<br /> How to copy the Stack to an existing
<br /> one-dimensional Array, starting at the specified array index
</h2>
<hr width="575" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="MediumVioletRed"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack CopyTo() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to count Stack elements


Count Stack elements



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we can count Stack elements. In this .net c# tutorial code, we used the Stack class Count property to count Stack items.




The Stack class Count property gets the number of elements contained in the Stack. The Stack Count property value is an Int32 which is the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store but the Count is the number of elements that are actually in the Stack.




StackCountProperty.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("DarkSeaGreen");
colors.Push("SpringGreen");
colors.Push("OliveDrab");
colors.Push("OrangeRed");
colors.Push("HotPink");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=OrangeRed>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

Label1.Text += "<br /><br />Total Stack Elements: " + colors.Count;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Stack Count - How to Get the number of elements contained in the Stack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack Count Property
<br /> How to Get the number of elements contained in the Stack
</h2>
<hr width="575" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="SlateBlue"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack Count Property"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to check whether an element is in the stack


Determine whether an item is in the Stack



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we can check whether an item is in the Stack or not. In this .net c# tutorial code, we used the Stack class Contains() method to determine whether an element exists in the Stack instance.




The Stack class Contains(Object) method allows us to determine whether an element is in the Stack. The Stack class Contains(object? obj) method has a parameter named obj. The obj parameter is the object to locate in the Stack. The value can be null.




The Stack class Contains(Object) method returns a Boolean value. The method returns true if the obj is found in the Stack otherwise it returns false. This method determines equality by calling the Object.Equals method. The method performs a linear search




StackContainsMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("BurlyWood");
colors.Push("SaddleBrown");
colors.Push("SandyBrown");
colors.Push("Ivory");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=SlateBlue>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

Label1.Text += "<br /><br />Is Element 'Ivory' Exists In Stack? " + colors.Contains("Ivory");
Label1.Text += "<br />Is Element 'Salmon' Exists In Stack? " + colors.Contains("Salmon");
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to determine whether an element is in the Stack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack Contains() Method
<br /> How to determine whether an element is in the Stack
</h2>
<hr width="475" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="SteelBlue"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack Contains() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to remove all objects from the stack


Remove all objects from the Stack



The Stack class represents a simple last-in-first-out non-generic collection of objects. The Stack capacity is the number of elements it can hold. When elements are added to a Stack, its capacity is automatically increased as required through reallocation. The Stack accepts null as a valid value and allows duplicate elements.




The following .net c# tutorial code demonstrates how we can remove all objects from the Stack. That means we will delete all elements from a Stack instance. In this .net c# tutorial code, we used the Stack class Clear() method to remove all items from a Stack instance.




The Stack class Clear() method removes all objects from the Stack. This method set the Count is zero, and references to other objects from elements of the collection are also released.




StackClearMethod.aspx



<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Stack colors = new Stack();

colors.Push("Magenta");
colors.Push("Maroon");
colors.Push("MediumSeaGreen");
colors.Push("Lavender");

Label1.Text = "Stack Elements... ";
Label1.Text += "<font color=Tomato>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";

//this line remove all elements from Stack.
colors.Clear();

Label1.Text += "<br /><br />After Call Clear() Method, Stack Elements... ";
Label1.Text += "<font color=Tomato>";
foreach (string color in colors)
{
Label1.Text += "<br />" + color;
}
Label1.Text += "</font>";
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to remove all objects from the Stack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
System.Collections.Stack Clear() Method
<br /> How to remove all objects from the Stack
</h2>
<hr width="375" align="left" color="Navy" />
<br />
<asp:Label
ID="Label1"
runat="server"
ForeColor="SteelBlue"
Font-Size="Large"
Font-Names="Courier New"
Font-Italic="true"
Font-Bold="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Stack Clear() Method"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>




c# - How to make an ArrayList read-only

Make an ArrayList read-only
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can make an ArrayList read-only. That means we will convert an ArrayList instance to a read-only ArrayList. We also check whether an ArrayList instance is read-only or not. Here we will use the ArrayList class ReadOnly() method to make an ArrayList read-only. We also use the ArrayList class IsReadOnly property to determine whether an ArrayList is read-only or not.

A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection. If changes are made to the underlying collection, the read-only collection reflects those changes. A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created.

The ArrayList ReadOnly() method returns a list wrapper that is read-only. The ArrayList ReadOnly(ArrayList) method overload returns a read-only ArrayList wrapper. The ArrayList ReadOnly(System.Collections.ArrayList list) method overload has a parameter named list. The list parameter is the ArrayList to wrap. This method returns a read-only ArrayList wrapper around the list. The method throws ArgumentNullException if the list is null.

The ArrayList class IsReadOnly property gets a value indicating whether the ArrayList is read-only. The property returns true if the ArrayList is read-only otherwise it returns false. The default value is false.
ArrayListIsReadOnlyProperty.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() { "Salmon", "SandyBrown", "Gray" };

        Label1.Text = "<font color=DodgerBlue>'colors' ArrayList Elements... ";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        ArrayList readOnlyColors = ArrayList.ReadOnly(colors);

        Label1.Text += "<br /><br />Is 'colors' ArrayList ReadOnly? " + colors.IsReadOnly.ToString();
        Label1.Text += "<br />Is 'readOnlyColors' ArrayList ReadOnly? " + readOnlyColors.IsReadOnly.ToString();

        colors.Add("White");

        //Uncomment this line to get error message.
        //readOnlyColors.Add("White");

        Label1.Text += "<br /><br /><font color=DodgerBlue>After Adding 'White', Now 'colors' ArrayList Elements... ";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to create a read-only copy of the ArrayList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList IsReadOnly Property
            <br /> How to create a read-only copy of the ArrayList
        </h2>
        <hr width="525" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="HotPink"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList IsReadOnly Property"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to copy elements over a range in ArrayList

Copy the elements of a collection over a range of elements in an ArrayList
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can copy the elements of a collection over a range of elements in an ArrayList instance. Here we will use the ArrayList class SetRange() method to copy elements over a range of elements in the ArrayList object.

The ArrayList SetRange(Int32, ICollection) method copies the elements of a collection over a range of elements in the ArrayList. The order of the elements in the ICollection is preserved in the ArrayList. The ArrayList SetRange(int index, System.Collections.ICollection c) method has two parameters.

The index parameter is the zero-based ArrayList index at which to start copying the elements of c. And the c parameter is the ICollection whose elements to copy to the ArrayList. The collection itself cannot be null, but it can contain elements that are null.

The ArrayList SetRange(Int32, ICollection) method throws ArgumentOutOfRangeException if the index is less than zero or the index plus the number of elements in c is greater than Count. It throws ArgumentNullException if the c is null. The method also throws NotSupportedException if the ArrayList is read-only.
ArrayListSetRangeMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() { "Red", "IndianRed", "PaleVioletRed", "DarkRed", "Lavender","Snow" };

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=SeaGreen>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        List<string> pinkColors = new List<string>() {"Pink","DeepPnk","HotPink" };
        colors.SetRange(2,pinkColors);

        Label1.Text += "<br /><br />List Elements(ICollection)....";
        Label1.Text += "<font color=SlateBlue>";
        foreach (string color in pinkColors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        Label1.Text += "<br /><br />After Call SetRange(index 2, ICollection) Method";
        Label1.Text += "<br />Now ArrayList Elements....";
        Label1.Text += "<font color=DeepPink>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ArrayList SetRange() - How to copy the elements of a collection over a range of elements in the ArrayList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList SetRange() Method
            <br /> How to copy the elements of a collection
            <br /> over a range of elements in the ArrayList
        </h2>
        <hr width="425" align="left" color="Navy" />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="DarkSalmon"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList SetRange() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to reverse ArrayList range of elements order

Reverse order of a range of elements in an ArrayList
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can reverse the order of a range of elements in an ArrayList instance. That means we will reverse the order of the elements in a specified range within an ArrayList object. Here we will use the ArrayList class Reverse() method to reverse a range of element’s order.

The ArrayList Reverse() method reverses the order of the elements in the ArrayList or a portion of it. The ArrayList class Reverse(Int32, Int32) method overload reverses the order of the elements in the specified range.

The ArrayList Reverse(int index, int count) method has two parameters. The index parameter is The zero-based starting index of the range to reverse. And the count parameter is The number of elements in the range to reverse.

The ArrayList Reverse(int index, int count) method throws several exceptions. It throws ArgumentOutOfRangeException if the index is less than zero or the count is less than zero. The method throws ArgumentException if the index and count do not denote a valid range of elements in the ArrayList. And it also throws NotSupportedException if the ArrayList is read-only.
ArrayListReverseMethodWithRange.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() { "DimGray", "Gold", "Green", "Ivory", "LightSalmon" };

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=SeaGreen>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        colors.Reverse(1,3);

        Label1.Text += "<br /><br />After Call Reverse(index 1, count 3) Method";
        Label1.Text += "<br />Now ArrayList Elements....";

        Label1.Text += "<font color=DeepPink>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ArrayList - How to reverse the order of the elements in the specified range</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList Reverse(Int32, Int32) Method
            <br /> How to reverse the order of the elements in the specified range
        </h2>
        <hr width="625" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="DarkSalmon"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList Reverse(Int32, Int32) Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to remove a range of elements from ArrayList

Remove a range of elements from an ArrayList
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can remove a range of elements from an ArrayList instance at once. That means we will delete multiple elements from an ArrayList object. Here we will use the ArrayList class RemoveRange() method to remove a range of elements from an ArrayList instance.

The ArrayList RemoveRange(Int32, Int32) method removes a range of elements from the ArrayList. The RemoveRange(int index, int count) method has two parameters. The index parameter is the zero-based starting index of the range of elements to remove. And the count parameter is the number of elements to remove.

The RemoveRange(int index, int count) method throws ArgumentOutOfRangeException if the index is less than zero or the count is less than zero. It throws ArgumentException if the index and count do not denote a valid range of elements in the ArrayList. It also throws NotSupportedException if the ArrayList is read-only or the ArrayList has a fixed size.

So finally, using the ArrayList class RemoveRange() method the .net c# developers can delete multiple elements from an ArrayList instance at once. It removes a range of elements from an ArrayList object.
ArrayListRemoveRangeMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() { "Pink", "Peru", "Plum", "Snow", "Blue","White" };

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=DeepBlue>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        colors.RemoveRange(2,3);

        Label1.Text += "<br /><br />After Call RemoveRange(index 2, count 3) Method";
        Label1.Text += "<br />Now ArrayList Elements....";
        Label1.Text += "<font color=DarkSlateGray>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to remove a range of elements from ArrayList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList RemoveRange() Method
            <br /> How to remove a range of elements from the ArrayList
        </h2>
        <hr width="575" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="Orchid"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList RemoveRange() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to insert multiple elements into an ArrayList

Insert multiple elements into an ArrayList at once
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can insert multiple elements into an ArrayList at once. That means we add a collection of elements into an ArrayList at the specified index position. Here we will use the ArrayList class InsertRange() method to add multiple elements to an ArrayList instance.

The ArrayList InsertRange(Int32, ICollection) method inserts the elements of a collection into the ArrayList at the specified index. The ArrayList InsertRange(int index, System.Collections.ICollection c) method has two parameters. The index parameter is the zero-based index at which the new elements should be inserted. And the c parameter is the ICollection whose elements should be inserted into the ArrayList. The collection itself cannot be null, but it can contain elements that are null.

The ArrayList InsertRange(index, c) method throws several exceptions. The method throws ArgumentNullException if the c is null. It throws ArgumentOutOfRangeException if the index is less than zero or the index is greater than Count. This method throws NotSupportedException if the ArrayList is read-only or the ArrayList has a fixed size.

So finally, using the ArrayList class InsertRange() method the .net c# developers can add multiple elements to an ArrayList instance at once at its specified index position.
ArrayListInsertRangeMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() {"Green","SeaGreen","SpringGreen","LawnGreen"};

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=Green>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        List<string> redColors = new List<string>() {"Red","DarkRed","IndianRed" };
        colors.InsertRange(2,redColors);

        Label1.Text += "<br /><br />After call InsertRange(index 2, ICollection) Method";
        Label1.Text+= "<br /><u>Now ArrayList Elements</u>...";
        Label1.Text += "<font color=Red>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to insert the elements of a collection into the ArrayList at the specified index</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList InsertRange() Method
            <br /> How to insert the elements of a collection
            <br /> into the ArrayList at the specified index
        </h2>
        <hr width="475" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="Orchid"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList InsertRange() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to get the index of an element within a range in ArrayList

Get the index of an element within a range of elements in an ArrayList
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can get the index of an element within a range of elements in an ArrayList. That means we will find the specified element within a range of elements in an ArrayList. Here we will use the ArrayList class IndexOf() method to get the index of an element within a range in an ArrayList object. We only take the index of the element’s first occurrence within a range of elements in an ArrayList.

The ArrayList IndexOf() method returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it. The ArrayList IndexOf(Object, Int32, Int32) method overload searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that starts at the specified index and contains the specified number of elements.

The ArrayList IndexOf(object? value, int startIndex, int count) method overload has three parameters. The value parameter is the Object to locate in the ArrayList. The value can be null. The startIndex parameter is the zero-based starting index of the search. 0 (zero) is valid in an empty list. And the count parameter is the number of elements in the section to search.

The ArrayList IndexOf(object? value, int startIndex, int count) method returns the zero-based index of the first occurrence of value within the range of elements in the ArrayList that starts at startIndex and contains the count number of elements if found otherwise it returns -1.

The ArrayList IndexOf(object? value, int startIndex, int count) method throws ArgumentOutOfRangeExceptionIf the startIndex is outside the range of valid indexes for the ArrayList or the count is less than zero or the startIndex and count do not specify a valid section in the ArrayList. The ArrayList is searched forward starting at startIndex and ending at startIndex plus count minus 1 if the count is greater than 0.
ArrayListIndexOfMethodWithStartIndexAndCount.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() { "ForestGreen", "Orange", "SkyBlue", "Navy", "Orange", "Olive" };

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=SkyBlue>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        Label1.Text += "<br /><br />IndexOf(object Orange, startIndex 2, count 4)";
        Label1.Text += "<font color=Crimson>";
        Label1.Text += "<br />Index of 'Orange': " + colors.IndexOf("Orange", 2, 4);
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use System.Collections.ArrayList IndexOf(Object, Int32, Int32) Method</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList IndexOf(Object, Int32, Int32) Method
            <br /> How to search specified Object and get zero-based index of first
            <br /> occurrence within the range of elements in ArrayList that starts
            <br /> at specified index and contains specified number of elements
        </h2>
        <hr width="575" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="DarkOrchid"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList IndexOf(Object, Int32, Int32) Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to get an element index in ArrayList by the starting index

Get an element index from ArrayList by specified starting index
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can get the index of an element in an ArrayList instance by using the starting index. That means we will find the specified element within ArrayList from the specified index position. Here we will use the ArrayList class IndexOf() method to get the index of an element in an ArrayList object. We only take the index of the element’s first occurrence within an ArrayList from the specified index position.

The ArrayList IndexOf() method returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it. The ArrayList IndexOf(Object, Int32) method overload searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that extends from the specified index to the last element.

The ArrayList IndexOf(object? value, int startIndex) method overload has two parameters those are value and startIndex. The value parameter is the Object to locate in the ArrayList. The value can be null. And the startIndex parameter is the zero-based starting index of the search. 0 (zero) is valid in an empty list.

The ArrayList IndexOf(object? value, int startIndex) method returns the zero-based index of the first occurrence of value within the range of elements in the ArrayList that extends from startIndex to the last element if found otherwise it returns -1.

The ArrayList IndexOf(object? value, int startIndex) method throws ArgumentOutOfRangeException if the startIndex is outside the range of valid indexes for the ArrayList. The ArrayList is searched forward starting at startIndex and ending at the last element.
ArrayListIndexOfMethodWithStartIndex.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() {"Green","Blue","Red","Peru","Blue","Salmon"};

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=DarkOrange>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        Label1.Text += "<br /><br />IndexOf(object Blue, startIndex 2)";
        Label1.Text += "<font color=DarkGreen>";
        Label1.Text += "<br />Index of 'Blue': " + colors.IndexOf("Blue", 2);
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to search specified Object, get zero-based index of first occurrence within the range of elements in ArrayList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList IndexOf(Object, Int32) Method
            <br /> How to search specified Object, get zero-based index
            <br /> of first occurrence within the range of elements in ArrayList
        </h2>
        <hr width="575" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="DarkOrchid"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList IndexOf(Object, Int32) Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to get the index of an ArrayList element

Get the index of an element in ArrayList
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The ArrayList capacity is the number of elements it can hold. Its capacity is automatically increased while adding elements. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can get the index of an element in an ArrayList instance. Here we will use the ArrayList class IndexOf() method to get the index of an element in an ArrayList object. We only take the index of the element’s first occurrence within an ArrayList.

The ArrayList IndexOf() method returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it. The ArrayList IndexOf(Object) method overload searches for the specified Object and returns the zero-based index of the first occurrence within the entire ArrayList.

The ArrayList IndexOf(object? value) method overload has a parameter named value. The value parameter is the Object to locate in the ArrayList. The value can be null. The method returns the zero-based index of the first occurrence of value within the entire ArrayList if found otherwise it returns -1.

The ArrayList is searched forward starting at the first element and ending at the last element. The ArrayList IndexOf() method performs a linear search. The ArrayList IndexOf() method determines equality by calling Object.Equals.
ArrayListIndexOfMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() {"Olive","HotPink","White","Peru","Pink","Yellow"};

        Label1.Text = "ArrayList Elements....";
        Label1.Text += "<font color=DodgerBlue>";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        Label1.Text += "<font color=HotPink>";
        Label1.Text += "<br /><br />Index of 'White': " + colors.IndexOf("White");
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to search specified Object and get zero-based index of the first occurrence within the entire ArrayList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList IndexOf() Method
            <br /> How to search specified Object and get zero-based
            <br /> index of the first occurrence within the entire ArrayList
        </h2>
        <hr width="550" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="Green"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList IndexOf() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to copy a range of ArrayList elements to an Array

Copy a range of elements from the ArrayList to an Array
The ArrayList class implements the IList interface using an array whose size is dynamically increased as required. It is designed to hold heterogeneous collections of objects. ArrayList is not guaranteed to be sorted. The capacity of an ArrayList is the number of elements the ArrayList can hold. As elements are added to an ArrayList, the capacity is automatically increased. ArrayList elements can be accessed by index and it is zero-based. The ArrayList accepts null as a valid value and also allows duplicate elements.

The following .net c# tutorial code demonstrates how we can copy an ArrayList specified elements (a range of elements) to an Array. Here we used the ArrayList class CopyTo() method to copy an ArrayList to an Array instance.

The ArrayList CopyTo() method copies the ArrayList or a portion of it to a one-dimensional array. The ArrayList CopyTo(Int32, Array, Int32, Int32) method overload copies a range of elements from the ArrayList to a compatible one-dimensional Array, starting at the specified index of the target array.

The ArrayList CopyTo(int index, Array array, int arrayIndex, int count) method overload’s index parameter is the zero-based index in the source ArrayList at which copying begins. The array parameter is the one-dimensional Array that is the destination of the elements copied from ArrayList. The Array must have zero-based indexing. The arrayIndex parameter is the zero-based index in the array at which copying begins. And the count parameter is the number of elements to copy.

The ArrayList CopyTo(int index, Array array, int arrayIndex, int count) method overload throws several exceptions such as it throws ArgumentNullException if the array is null. Throws ArgumentOutOfRangeExceptionif the index is less than zero or the arrayIndex is less than zero or the count is less than zero. It also throws InvalidCastException if the type of the source ArrayList cannot be cast automatically to the type of the destination array.

So finally, using the ArrayList CopyTo() method the .net developers can copy an ArrayList or a portion of it to a one-dimensional Array instance.
ArrayListCopyToMethodWithElementsRange.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        ArrayList colors = new ArrayList() {"Red","DarkRed","IndianRed","MediumVioletRed"};

        Label1.Text = "ArrayList Elements....";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }

        string[] colorArray = {"Olive","OliveDrab","SeaGreen","ForestGreen","MediumSeaGreen"};
        Label1.Text += "<font color=SeaGreen>";
        Label1.Text += "<br /><br />Array Elements...";
        foreach (string color in colorArray)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";

        colors.CopyTo(1,colorArray,2,2);
        Label1.Text += "<font color=OrangeRed>";
        Label1.Text += "<br /><br />After Call CopyTo(Int32, Array, Int32, Int32) Method";
        Label1.Text += "<br />CopyTo(List Index 1, Array, arrayindex 2, count 2) Array Elements...";
        foreach (string color in colorArray)
        {
            Label1.Text += "<br />" + color;
        }
        Label1.Text += "</font>";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to copy a range of elements from the ArrayList to a compatible Array, starting at the specified index of the array</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:MidnightBlue; font-style:italic;">
            System.Collections.ArrayList CopyTo(Int32, Array, Int32, Int32) Method
            <br /> How to copy ArrayList to a compatible
            <br /> Array, starting at the specified index of the array
        </h2>
        <hr width="525" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="Crimson"
             Font-Size="Large"
             Font-Names="Courier New"
             Font-Italic="true"
             Font-Bold="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test ArrayList CopyTo(Int32, Array, Int32, Int32) Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to convert Dictionary keys into array

How to convert Dictionary Keys into array
.Net framework Dictionary<TKey, TValue> class represents a collection of keys and values. the Dictionary<TKey, TValue>.Keysproperty allow us to get a collection containing the keys in the Dictionary<TKey, TValue>. this Keys property value type isSystem.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.

to convert a dictionary keys to array, first we need to get the dictionary keys by its 'Keys' property. this property return acollection (generic list) of dictionary keys. after getting the List<T>, we can convert it to an array by List class ToArray() method.

List<T>.ToArray() method allow us to copy the elements of the List<T> to a new array. so we can convert the dictionary keys into array asDictionary<TKey, TValue>.Keys.ToArray().

the following asp.net c# example code demonstrate us how can we convert dictionary keys to an array programmaticallyat run time in an asp.net application.
ConvertDictionaryKeysIntoArray.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Dictionary<string, string> colors = new Dictionary<string, string>();
        colors.Add("Fuchsia", "#FF00FF");
        colors.Add("GoldenRod", "#DAA520");
        colors.Add("Lavender", "#E6E6FA");
        colors.Add("LightGreen", "#90EE90");

        Label1.Text = "Dictionary Keys | Values.....<br />";
        foreach(KeyValuePair<string,string> pair in colors)
        {
            Label1.Text += "Key= "+pair.Key +" | Value= "+ pair.Value + "<br />";
        }

        string[] colorKeyArray = colors.Keys.ToArray();
        Label1.Text += "<br />Color Array Items....";
        foreach (string color in colorKeyArray)
        {
            Label1.Text += "<br />" + color;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to convert Dictionary Keys into array</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Crimson; font-style:italic;">
            System.Collections.Generic.Dictionary
            <br /> How to convert Dictionary Keys into array
        </h2>
        <hr width="450" align="left" color="DeepPink" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="DodgerBlue"
             Font-Names="Courier New"
             Font-Size="X-Large"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Convert Dictionary Keys into array"
            Height="45"
            Font-Bold="true"
            ForeColor="Navy"
            />
    </div>
    </form>
</body>
</html>

c# - How to get a range of elements from a list

Generic List GetRange() Method
.Net framework generic list GetRange() method allow us to create a shallow copy of a range of elements in the source List<T>.the GetRange() method is exists under System.Collections.Generic namespace. this method require to pass two parameters, named 'index' and 'count'.

both 'index' and 'count' parameters data type is System.Int32. the 'index' represent the zero based List<T> index at which the range startsand the 'count' represent the number of elements in the range.

this method return value type is System.Collections.Generic.List<T>. this returned List<T> is a shallow copy of a range of elements in the sourceList<T>. this method throw ArgumentOutOfRangeException exception if the 'index' is less than zero (0) or 'count' is less than 0. this method also throwArgumentException exception if the 'index' and 'count' do not denote a valid range of elements in the List<T>.

the following asp.net c# example code demonstrate us how can we get a shallow copy of a range of elements in the source generic listin an asp.net application.
GenericListGetRangeMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        List<string> colors = new List<string>() {"DarkRed","Purple","MediumPurple"};
        colors.Add("Maroon");
        colors.Add("MediumBlue");
        colors.Add("Orange");
        colors.Add("OrangeRed");

        Label1.Text = "List Elements....<br />";
        foreach (string color in colors)
        {
            Label1.Text += "<br />" + color;
        }

        string[] colorArray = colors.GetRange(2, 3).ToArray();

        Label1.Text += "<br /><br />After Call GetRange(2,3) Method Array Elements are.....<br />";

        foreach (string color in colorArray)
        {
            Label1.Text += "<br />" + color;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Generic List GetRange() - How to create a shallow copy of a range of elements in the source List</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:SlateBlue; font-style:italic;">
            System.Collections.Generic.List GetRange() Method
            <br /> How to create a shallow copy of a range of elements in the source List
        </h2>
        <hr width="650" align="left" color="Purple" />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="DarkOrchid"
             Font-Size="Large"
             Font-Names="Courier New"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test Generic List GetRange() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

asp.net - Deselect Calendar selected date on second click

Deselect Calendar selected date on second click
Calendar is an asp.net rich web server control that provide us a way to select an individual dateor date range. this example code demonstrate us an interesting technique to deselect calendar selected date on second click.

first click on any date cell we can select a date from calendar control and we can change the selection of calendar date by selectinganother date or date range from calendar control. calendar server control has no built in feature to deselect selected date on second clickand it has no feature to select random date from calendar control.

to select random date from calendar control and deselect selected date on second click we need to apply few techniques.to do this we created an event handler for calendar SelectionChanged event. we stored the calendar selected dates in a bulletedlist items collection.when users click a date in calendar control then we test it that the buletedlist items contains the clicked date. if we found the selected datein bulletedlist items then it is the second click of same date. if it second click of a date in calendar control then we removed it from bulltedlistitems collection and calendar selected dates collection. finally it deselect the calendar selected date on second click.

the following asp.net c# example code demonstrate us how can we deselect calendar selected date on second click.
DeselectCalendarSelectedDateOnSecondClick.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (Page.IsPostBack && Calendar1.SelectedDates.Count ==1)
        {
            Calendar1.SelectedDates.Clear();
        }
    }

    protected void Calendar1_SelectionChanged(object sender, System.EventArgs e)
    {
        ListItem li = new ListItem();
        li.Text = Calendar1.SelectedDate.ToShortDateString();

        int counter = 0;
        foreach (ListItem litem in BulletedList1.Items)
        {
            if (litem.Text == li.Text)
            {
                counter += 1;
            }
        }

        if (counter > 0)
        {
            BulletedList1.Items.Remove(li);
        }
        else
        {
            BulletedList1.Items.Add(li);
        }

        Calendar1.SelectedDates.Clear();
        SelectedDatesCollection dates = Calendar1.SelectedDates;

        foreach (ListItem litem in BulletedList1.Items)
        {
            DateTime date = Convert.ToDateTime(litem.Text);
            dates.Add(date);
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to deselect Calendar selected date on second click</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:SlateBlue; font-style:italic;">
            How to deselect Calendar selected date on second click
        </h2>
        <hr width="600" align="left" color="SlateGray" />
        <asp:BulletedList
             ID="BulletedList1"
             runat="server"
             Visible="false"
             >
        </asp:BulletedList>
        <asp:Calendar
            ID="Calendar1" 
            runat="server"
            NextPrevFormat="FullMonth"
            ForeColor="WhiteSmoke"
            SelectionMode="Day"
            DayNameFormat="Full"
            Font-Names="Book Antiqua"
            Font-Size="Medium"
            OnSelectionChanged="Calendar1_SelectionChanged"
            >
            <DayHeaderStyle
                 BackColor="OliveDrab"
                 />
            <DayStyle
                 BackColor="DarkOrange"
                 BorderColor="Orange"
                 BorderWidth="1"
                 Font-Bold="true"
                 Font-Italic="true"
                 Font-Size="Large"
                 />
            <NextPrevStyle
                 Font-Italic="true"
                 Font-Names="Arial CE"
                 />
            <OtherMonthDayStyle BackColor="Tomato" />
            <SelectedDayStyle
                 BackColor="Green"
                 BorderColor="MediumSeaGreen"
                 />
            <TitleStyle
                 BackColor="MidnightBlue"
                 Height="36"
                 Font-Size="Large"
                 Font-Names="Courier New Baltic"
                 />
        </asp:Calendar>
    </div>
    </form>
</body>
</html>

asp.net - How to add custom text to a day cell in a Calendar

Add custom text in Calendar Individual Day Cell
Calendar is an ASP.NET web server control. Users can select an individual date or date range in a Calendar control. Calendar OnDayRender() method raises the DayRender event of calendar control that allows us to write a custom handler for the DayRender event. The Calendar DayRender event occurs when each day is created in the control hierarchy for the Calendar control.

We can add static control to a calendar’s specific date cell before Calendar display in a web browser such as Literal, Image, and Hyperlink control. ASP.NET Literal server control reserves a location on the web page to display static text. So if we can add a Literal control on the Calendar individual date cell then we can add any static text to any date cell in the Calendar control.

First, we need to create a Literal control programmatically in the DayRender event handler section. Then we add static text to Literal control which we want to display in the calendar’s specific date cell. After creating the Literal control we add it to the individual date cell. Finally, calendar control displays the static text on the specified date cell. We add the newly created Literal control to Calendar’s specific date cell control collection.

The following ASP.NET C# example code demonstrates to us how can we add custom text on the Calendar individual date cell in an ASP.NET application.
AddCustomTextInCalendarDayCell.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html>

<script runat="server">
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.Date == new DateTime(2008,10,7))
        {
            Literal Literal1 = new Literal();
            Literal1.Text ="<br /><font size=-1 color=Gold>Blog First Post</font>";

            e.Cell.Font.Italic = true;
            e.Cell.Font.Size = FontUnit.XLarge;
            e.Cell.BackColor = System.Drawing.Color.Crimson;
            e.Cell.BorderColor = System.Drawing.Color.Pink;
            e.Cell.ForeColor = System.Drawing.Color.Snow;
            e.Cell.Font.Name = "Courier New";

            e.Cell.Controls.AddAt(1,Literal1);
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to add custom text in Calendar Day Cell</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:SlateBlue; font-style:italic;">
            How to add custom text in Calendar Day Cell
        </h2>
        <hr width="475" align="left" color="SlateGray" />
        <asp:Calendar
            ID="Calendar1" 
            runat="server"
            NextPrevFormat="FullMonth"
            ForeColor="WhiteSmoke"
            SelectionMode="Day"
            DayNameFormat="Full"
            Font-Names="Book Antiqua"
            Font-Size="Medium"
            OnDayRender="Calendar1_DayRender"
            VisibleDate="10/7/2008"
            >
            <DayHeaderStyle
                 BackColor="OliveDrab"
                 />
            <DayStyle
                 BackColor="DarkGreen"
                 BorderColor="ForestGreen"
                 BorderWidth="1"
                 Font-Bold="true"
                 Font-Italic="true"
                 Font-Size="Large"
                 />
            <NextPrevStyle
                 Font-Italic="true"
                 Font-Names="Arial CE"
                 />
            <SelectedDayStyle
                 BackColor="DarkBlue"
                 BorderColor="CornflowerBlue"
                 />
            <TitleStyle
                 BackColor="MidnightBlue"
                 Height="36"
                 Font-Size="Large"
                 Font-Names="Courier New Baltic"
                 />
        </asp:Calendar>
    </div>
    </form>
</body>
</html>