c# - How to intersect two arrays

Intersect two Arrays
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can intersect two array instances. But there is no built-in method in the Array class two intersect two Array objects. So in this .net c# tutorial code, we will use Enumerable Intersect() method to intersect two Array instances. Here we will intersect two integer-type Array instances.

The Enumerable Intersect() method produces the set intersection of two sequences. This method is located under System.Linq namespace. The Enumerable Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method overload produces the set intersection of two sequences by using the default equality comparer to compare values.

The Intersect(first, second) method’s first parameter is an IEnumerable<T> whose distinct elements that also appear in the second will be returned. The second parameter is an IEnumerable<T> whose distinct elements that also appear in the first sequence will be returned.

The Enumerable Intersect() method returns a sequence that contains the elements that form the set intersection of two sequences. The Intersect(first, second) method throws ArgumentNullException if the first or second is null.
array-intersect.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        int[] numbers = { 10,50,75};
        int[] morenumbers = { 50,65,75,400};

        Label1.Text = "numbers array.........<br />";
        foreach (int i in numbers)
        {
            Label1.Text += i.ToString() + "<br />";
        }

        Label1.Text += "<br />more numbers array.........<br />";
        foreach (int i in morenumbers)
        {
            Label1.Text += i.ToString() + "<br />";
        }

        var intersect = numbers.Intersect(morenumbers);

        Label1.Text += "<br />intersect of numbers array and more numbers array.........<br />";
        foreach (int i in intersect)
        {
            Label1.Text += i.ToString() + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array intersect</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array intersect
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array intersect"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to get value of a specified element of an array

Array get value
The following asp.net c# example code demonstrate us how can we get a specified element value froman array object programmatically at run time in an asp.net application. .Net framework's Array Class Array.GetValue()method get the value of the specified element in the current array.

Array.GetValue(Int32) overloaded method allow us to get the value at the specified position in the one-dimensional array.In this example, we uses this overloaded member. GetValue(Int32) method has a required parameter named 'index' which valuedata type is System.Int32. This parameter value contains a 32-bit integer that represent the position of the array elementto get.

Array.GetValue(Int32) method return a System.Object type value. Method return the element value at the specified positionin the one dimensional array.

So, to get a specified element value of an one-dimensional array by index number, we can call the GetValue(Int32) methodas this way Array.GetValue(ElementIndex). Finally, we get the specified element value.
array-getvalue.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Indian Robin",
            "Northern Wheatear",
            "Bluethroat",
            "Spotted Flycatcher",
            "Thrush Nightingale"
        };

        Label1.Text = "birds array.........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        string index1bird = birds.GetValue(1).ToString();
        string index3bird = birds.GetValue(3).ToString();

        Label1.Text += "<br />birds array index 1 bird is: " + index1bird;
        Label1.Text += "<br />birds array index 3 bird is: " + index3bird;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array getvalue</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array getvalue
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array getvalue"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to get a range of elements from an array

Get a range of elements from an Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can get a range of elements from an Array instance. That means we will get a specified number of elements from an Array instance and create a new instance of an Array object by the returned elements.

Here we will copy the specified elements from an Array object and create a new instance of an Array instance by copied elements. In this .net c# tutorial code we used the Array Copy() method to copy some elements from the source Array and create a new instance of an Array.

The Array Copy() method copies a range of elements in one Array to another Array and performs type casting and boxing as required. The Array Copy(Array, Int32, Array, Int32, Int32) method overload copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers. So using this method overload .net developers can get a range of elements from an Array instance and create another Array instance from copied elements.

The Array Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) method’s sourceArray parameter is the Array that contains the data to copy. The sourceIndex parameter is a 32-bit integer that represents the index in the sourceArray at which copying begins. The destinationArray parameter is the Array that receives the data. The destinationIndex parameter is a 32-bit integer that represents the index in the destinationArray at which storing begins. And the length parameter is a 32-bit integer that represents the number of elements to copy.

The Array Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) method throws several exceptions such as it throws ArgumentNullException if the sourceArray is null or the destinationArray is null. The method throws RankException if the sourceArray and destinationArray have different ranks. It throws ArrayTypeMismatchException if the sourceArray and destinationArray are of incompatible types.
array-get-range.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Wood Thrush",
            "Japanese Thrush",
            "Mistle Thrush",
            "Austral Thrush",
            "Green Cochoa"
        };

        Label1.Text = "birds array.........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        //new destination (copied) array length
        int length = 3;
        //copy start from index 1. second element from birds array.
        int index = 1;

        string[] copiedRange = new string[length];
        Array.Copy(birds, index, copiedRange, 0, length);

        Label1.Text += "<br />new array from birds array [index range 1 to 3].........<br />";
        foreach (string s in copiedRange)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array get range</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array get range
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array get range"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to filter an array elements

Array filter
The following asp.net c# example code demonstrate us how can we filter an array elements depends on specific criteriaand get a new array object with filtered elements programmatically at run time in an asp.net application. .Net framework'sArray Class Array.FindAll() method retrieve all the elements that match the conditions defined by the specified predicate.

Arry.FindAll<T>() method type parameter name is 'T' which represent the type of the elements of the array.FindAll() method has two required parameters named 'array' and 'match'. The 'array' parameter represent a one-dimensional arrayto search. And the 'match' parameter represent the Predicate<T> that defines the conditions of the elements to search for.

FindAll() method return an array object which contains all the elements that match the conditions. Finally, we can filter anarray and get a new array object with filtered elements as this way NewArray = Array.FindAll(Condition).
array-filter.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Rock Parrot",
            "Crimson Rosella",
            "Regent Parrot",
            "Superb Parrot",
            "Red Lory",
            "African Emerald Cuckoo"
        };

        Label1.Text = "birds array.........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        //this line filter birds array and populate a new array.
        string[] filteredbirds = Array.FindAll(birds, x => x.EndsWith("Parrot"));

        Label1.Text += "<br />filtered birds array [ends with 'Parrot'].........<br />";
        foreach(string s in filteredbirds)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array filter</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array filter
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array filter"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - Find index of last element from an array that match the conditions

Array find last index
The following asp.net c# example code demonstrate us, how can we get index of last occurrence of an element within an arraywhich elements are matches the search condition, programmatically at run time in an asp.net application.

.Net framework's Array Class Array.FindLastIndex() method searches for an element that matches the conditiondefined by a specified predicate, return the zero-based index of the last occurrence within an array or a portion of array.Array.FindLastIndex() method has few overloads.

ArrayFindLastIndex<T>(T[], Predicate<T>) overloaded method searches for an element that matches the conditions defined by thespecified predicate, and returns the zero-based index of the last occurrence within the entire array.

ArrayFindLastIndex(T[], Predicate<T>) method has two required parameters named 'array' and 'match'. The 'array' parameterrepresent the one-dimensional, zero-based array to search and 'match' parameter represent the Predicate<T> that definesthe conditions of the elements to search for.

ArrayFindLastIndex() method return an integer data type value which represent the zero-based index of the last occurrenceof an element that matches the conditions defined by 'match' parameter; otherwise it return -1.
array-findlastindex.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Greater Painted Snipe",
            "Northern Lapwing",
            "Hudsonian Godwit",
            "Masked Lapwing",
            "Black Oystercatcher"
        };

        Label1.Text = "birds array.........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        int lastindexofLapwing = Array.FindLastIndex(birds, x => x.EndsWith("Lapwing"));
        Label1.Text += "<br />last index of [Lapwing] in birds array: " + lastindexofLapwing.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array findlastindex</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array findlastindex
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array findlastindex"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to get the last element of an array

Get the last element of an Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can get the last element of an Array. But there is no built-in method in the Array class to get the last element from an Array object. So in this .net c# tutorial code example, we will use the Enumerable Last() method to get the Array last element.

The Enumerable Last() method returns the last element of a sequence. The Enumerable Last() method throws ArgumentNullException if the source is null. It also throws InvalidOperationException if the source sequence is empty.

The Enumerable Last() method has another overload that returns the last element of a sequence that satisfies a specified condition. In this .net c# tutorial code we also get the last element of an Array instance which element ends with a specified String.

So finally, using the Enumerable class Last() method the .net c# developers can get the last element from an Array instance.
array-last-element.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Eurasian Coot",
            "Okinawa Rail",
            "Water Rail",
            "Virginia Rail",
            "African Finfoot"
        };

        Label1.Text = "birds array.........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        string lastbird = birds.Last();
        string lastRail = birds.Last(x => x.EndsWith("Rail"));

        Label1.Text += "<br />last bird of birds array: " + lastbird;
        Label1.Text += "<br />last bird of birds array which ends with 'Rail: " + lastRail;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array last element</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array last element
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array last element"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to get the first element of an array

Get the first element of an Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can get the first element of an Array instance. But there is no direct built-in method in the Array class to get the first element from an Array object. So, in this .net c# tutorial code we will use the Enumerable class First() method to get the first element of an Array instance.

The Enumerable First() method returns the first element of a sequence. The Enumerable First<TSource>(IEnumerable<TSource>) method overload returns the first element of a sequence. Here the source parameter is the IEnumerable<T> to return the first element of. This method returns the first element in the specified sequence. It throws ArgumentNullException if the source is null and also throws InvalidOperationException if the source sequence is empty.

The Enumerable First<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) method overload returns the first element in a sequence that satisfies a specified condition. The First(source, predicate) method’s source parameter is an IEnumerable<T> to return an element from. And the predicate parameter is a function to test each element for a condition. So using this method overload .net developers can get the first element of an Array instance that satisfies the provided condition.

The Enumerable First(source, predicate) method overload returns the first element in the sequence that passes the test in the specified predicate function. It throws ArgumentNullException if the source or predicate is null. It also throws InvalidOperationExceptionif no element satisfies the condition in the predicate or the source sequence is empty.
array-first.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Philippine Eagle",
            "Crane Hawk",
            "Savanna Hawk",
            "Eastern Imperial Eagle",
            "Golden Eagle"
        };

        Label1.Text = "birds array.........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        string firstbird = birds.First();
        string firstHawk = birds.First(x => x.EndsWith("Hawk"));

        Label1.Text += "<br />first bird of birds array: " + firstbird;
        Label1.Text += "<br />first bird of birds array which ends with 'Hawk: " + firstHawk;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array first</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array first
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="array first"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to fill an array with a single value

Fill an Array with a single value
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can fill an Array instance with a single value. That means we will set the same value for an Array object’s all elements. But there is no built-in method in the Array class to fill an Array instance with the same value. So in this .net c# tutorial code example, we will use the Enumerable Repeat() and ToArray() methods to fill an Array object with a single value.

The Enumerable Repeat() method generates a sequence that contains one repeated value. The Enumerable Repeat() method has two parameters those are element and count. The element is the value to be repeated and the count is the number of times to repeat the value in the generated sequence.

The Enumerable Repeat() method returns an IEnumerable<T> that contains a repeated value. The Repeat() method throws ArgumentOutOfRangeException if the count is less than 0.

The Enumerable ToArray() method creates an array from an IEnumerable<T>. The Enumerable ToArray() method returns an Array that contains the elements from the input sequence. It throws ArgumentNullExceptionif the source is null.

In this .net c# example code we also fill an Array object with a single value using a for loop. We loop through all the elements of an Array object and set the same value for all of them.

So finally, using the Enumerable class Repeat() and ToArray() methods the .net c# developers can fill an Array with a single value.
fill-array-with-a-single-value.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        //initialize and fill a string array with word 'c#'
        string[] stringArray = Enumerable.Repeat("c#",5).ToArray();

        string[] anotherStringArray = new string[4];
        int[] intArray = new int[3];

        //fill a string array with word 'asp.net' using for loop
        for (int i = 0; i < anotherStringArray.Length;i++ )
        {
            anotherStringArray[i] = "asp.net";
        }

        //fill an int array with value '10' using for loop
        for (int i = 0; i < intArray.Length; i++)
        {
            intArray[i] = 10;
        }

        Label1.Text = "string array elements.........<br />";
        foreach(string s in stringArray)
        {
            Label1.Text += s + "<br />";
        }

        Label1.Text += "<br />another string array elements.........<br />";
        foreach (string s in anotherStringArray)
        {
            Label1.Text += s + "<br />";
        }

        Label1.Text += "<br />int array elements.........<br />";
        foreach (int i in intArray)
        {
            Label1.Text += i.ToString() + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - fill array with a single value</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - fill array with a single value
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   

            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="fill array with a single value"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to find all elements from an array that match the conditions

Find all elements from an Array that match conditions
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can find all elements from an Array instance that match conditions. That means we will get all elements that satisfy the search criteria from an Array object. And also create an Array instance by using the returned elements. In this .net c# tutorial code, we will use the Array class FindAll() method to find all elements from an Array that match specified conditions.

The Array FindAll() method retrieves all the elements that match the conditions defined by the specified predicate. The FindAll<T> (T[] array, Predicate<T> match) method has two parameters those are array and match. The array parameter is the one-dimensional, zero-based Array to search. And the match parameter is the Predicate<T> that defines the conditions of the elements to search for.

The Array FindAll() method returns an Array containing all the elements that match the conditions defined by the specified predicate if found otherwise it returns an empty Array. The Array FindAll(array, match) method throws ArgumentNullException if the array is null or the match is null.

So finally, using the Array FindAll() method .net developers can find elements from an Array instance that match conditions. In this tutorial, we pass a condition that the element ends with a specified String by ignoring the case. We used the String class EndsWith() method to check the condition.
array-findall.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Snow Goose",
            "Canada Goose",
            "Muscovy Duck",
            "Barnacle Goose",
            "Fairy Penguin"
        };

        Label1.Text = "birds array.........<br />";
        foreach (string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        //find all elements which match search query
        string[] endsWithGoose = Array.FindAll(birds, x => x.EndsWith("Goose", StringComparison.OrdinalIgnoreCase));

        Label1.Text += "<br />all birds ends with [Goose] birds array.........<br />";
        foreach (string s in endsWithGoose)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array findall</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array findall
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="X-Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="test array findall"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to find an element from an array

Find an element from an Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can find an element from an Array instance. That means we will find the first element from an Array object which meet the conditions. In this .net c# tutorial code, we used Array Find() method to find an element from an Array instance.

The Array Find() method searches for an element that matches the conditions defined by the specified predicate and returns the first occurrence within the entire Array. The Array Find<T> (T[] array, Predicate<T> match) method has two parameters those are array and match. The array parameter is the one-dimensional, zero-based array to search and the match parameter is the predicate that defines the conditions of the element to search for.

The Array Find() method returns the first element that matches the conditions defined by the specified predicate if found otherwise it returns the default value for type T. The Find(array, match) method throws ArgumentNullException if the array is null or the match is null. So finally, using the Array Find() method .net developers can find an element (first element) from an Array instance that match the conditions.
array-find.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Blue Duck",
            "Mandarin Duck",
            "Mallard",
            "Brown Teal",
            "Muscovy Duck"
        };

        Label1.Text = "birds array.........<br />";
        foreach (string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        //find only first element which match search query
        string startsWithB = Array.Find(birds, x => x.StartsWith("B"));
        string endsWithd = Array.Find(birds, x => x.EndsWith("d"));
        string endsWithduck = Array.Find(birds, x => x.EndsWith("duck",StringComparison.OrdinalIgnoreCase));

        Label1.Text += "<br />bird starts with [B]: " + startsWithB;
        Label1.Text += "<br />bird ends with [d]: " + endsWithd;
        Label1.Text += "<br />bird ends with [duck - ignore case]: " + endsWithduck;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array find</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array find
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="X-Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="test array find"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to make array except

Array Except
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can get the difference between two Array instances. Here we will compare two Array instances and get only the elements from the first Array that do not exist in the second Array instance. In this .net c# example code, we will use Enumerable Except() method to get the difference between two Array instances.

The Enumerable Except() method produces the set difference of two sequences. This method exists in the System.Linq namespace. The set difference between the two sets is defined as the members of the first set that do not appear in the second set.

The Enumerable Except() method returns those elements in the first sequence that do not appear in the second sequence. It does not return those elements in the second sequence that do not appear in the first sequence. Only unique elements are returned.

The Enumerable Except(first, second) method’s first parameter is a sequence whose elements that are not also in the second sequence will be returned. The second parameter is a sequence whose elements that also occur in the first sequence will cause those elements to be removed from the returned sequence.

The Enumerable Except(first, second) method returns a sequence that contains the set difference of the elements of two sequences. This method throws ArgumentNullException if the first sequence or the second sequence is null.
array-except.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] colors = { "red", "pink", "violet", "white", "snow" };
        string[] morecolors = { "red", "maroon", "magenta", "white" };

        Label1.Text = "colors array.........<br />";
        foreach (string s in colors)
        {
            Label1.Text += s + "<br />";
        }

        Label1.Text += "<br />more colors array.........<br />";
        foreach (string s in morecolors)
        {
            Label1.Text += s + "<br />";
        }

        var exceptResult = colors.Except(morecolors);

        Label1.Text += "<br />after remove all color from colors array ";
        Label1.Text += "<br />which exists in more colors array...............<br />";
        foreach (string s in exceptResult)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array except</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array except
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="test array except"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to check whether an element exists in an array

Array exists
The following asp.net c# example code demonstrate us how can we determine whether specified elements are exists in anarray based on search criteria. .Net framework's Array Class Array.Exists<T>() method allow us to determine whetherthe specified array contains one or more elements that match the conditions defined by the specified predicate.

Array.Exists<T>() method type parameter is 't' which represent the type of the elements of the array. This method hastwo required parameters named 'array' and 'match'. The 'array' parameter represent the one-dimensional, zero-based index array tosearch. The 'match' parameter value represent the Predicate<T> that defines the conditions of the elements to search for.

Array.Exists() method return a Boolean value. It return 'true', if array contains value that match the condition; otherwiseit return 'false'.

In this example code, we call the Array.Exists() method three times. First and second call, we check whether array contain anelement with value 'skyblue' and 'green.' Third call, we search the array for elements whose value ends with character 'd'.
array-exists.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] colors = new string[]
        {
            "blue",
            "darkblue",
            "skyblue",
            "deepblue",
            "red"
        };

        Label1.Text = "colors array.........<br />";
        foreach (string s in colors)
        {
            Label1.Text += s + "<br />";
        }

        Boolean skyblueExists = Array.Exists(colors, x => x == "skyblue");
        Boolean greenExists = Array.Exists(colors, x => x == "green");
        Boolean colorEndEithd = Array.Exists(colors, x=> x.EndsWith("d"));

        Label1.Text += "<br />skyblue color exists in color array? " + skyblueExists.ToString();
        Label1.Text += "<br />green color exists in color array? " + greenExists.ToString();
        Label1.Text += "<br />any color end with 'd' exists in color array? " + colorEndEithd.ToString();
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array exists</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array exists
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="test array exists"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to delete an element from an array

Delete an element from an Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can delete an element from an Array. That means we will remove/delete an element from an Array instance and reduce the Array length and reallocate the Array elements. But there is no direct method in the Array class to delete an element from an Array object.

So we have to perform a series of tasks to delete an element from the Array object. In this .net c# example code, we will use the Array class Resize() method, Enumerable class ToList() method and List class RemoveAt() method to delete/remove an element from an Array instance.

In the beginning, we will convert the Array instance to a List object by using the Enumerable class ToList() method. Then we will remove the specified item from the List instance using the List class RemoveAt() method. Then we will resize the Array instance using the Array class Resize() method. We will set the Array new length to less than one instead of the original Array length.

Finally, we will iterate through the Array elements and reset their element value. As a result, the specified Array element will be deleted from the Array instance.

The Enumerable ToList() method creates a List<T> from an IEnumerable<T>. The List RemoveAt() method removes the element at the specified index of the List<T>.The Array Resize() method changes the number of elements of a one-dimensional Array to the specified new size.
array-delete-element.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Crimson Sunbird",
            "Italian Sparrow",
            "Russet Sparrow",
            "Swahili Sparrow",
            "Painted Finch"
        };

        Label1.Text = "birds array.........<br />";
        foreach (string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        List<string> birdslist = birds.ToList();
        birdslist.RemoveAt(2);

        Array.Resize(ref birds,birds.Length -1);

        for(int i=0;i<birds.Length;i++)
        {
            birds[i] = birdslist[i];
        }

        Label1.Text += "<br />birds array [after remove element from index 2].........<br />";
        foreach (string s in birds)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - array delete element</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - array delete element
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="delete array element"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to perform binary search on an array

Perform a binary search on an Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can perform a binary search on an Array instance. Binary search on an Array instance is worked on a sorted Array. So, we have to sort an Array instance first, and then we have to perform the binary search on the sorted Array instance. In this .net c# tutorial code, we used Array Sort() and BinarySearch() methods to perform a binary search on an Array instance.

The Array Sort() method sorts the elements in a one-dimensional array. The Array BinarySearch() method searches a one-dimensional sorted Array for a value, using a binary search algorithm. The Array BinarySearch(Array, Object) method overload searches an entire one-dimensional sorted array for a specific element, using the IComparable interface implemented by each element of the array and by the specified object.

The Array BinarySearch(Array, Object) method returns the index of the specified value in the specified array if the value is found otherwise it returns a negative number. The BinarySearch (Array array, object? value) method throws several exceptions such as it throws ArgumentNullException if the array is null. It also throws RankException if the array is multidimensional. The method throws ArgumentException if the value is of a type that is not compatible with the elements of the array.
array-binary-search.aspx

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

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)    
    {  
        string[] colors = new string[]  
        {  
            "white",  
            "green",  
            "yellow",  
            "blue",  
            "pink",  
        };

        Label1.Text = "colors array.........<br />";
        foreach (string s in colors)
        {
            Label1.Text += s + "<br />";
        }

        //binary search work correctly only on a pre sorted array.
        Array.Sort(colors);

        Label1.Text += "<br />sorted colors array.........<br />";
        foreach (string s in colors)  
        {  
            Label1.Text += s + "<br />";  
        }

        int index = Array.BinarySearch(colors, "pink");
        Label1.Text += "<br />index of color [pink] by binary search = " + index.ToString();
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - array binary search</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:DarkBlue; font-style:italic;">    
            c# example - array binary search
        </h2>    
        <hr width="550" align="left" color="LightBlue" />      
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"    
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="test array binary search"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to convert a string array to a comma separated string

Convert a String Array to a comma-separated String
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a String Array instance to a comma-separated String object. That means we will get a String instance from the elements of a String Array where the String instance contains the Array elements separated by comma delimiter. Here we will join the String Array elements with the comma separator and build an instance of the String object. In this .net c# example code, we will use the String class Join() method.

The String Join(String, String[]) method overload concatenates all the elements of a String array, using the specified separator between each element. The Join (string? separator, params string?[] value) method overload has two parameters those are separator and value. Here the separator parameter is the String to use as a separator and the value parameter is an Array that contains the elements to concatenate.

So, using this method overload we can join String Array elements to get a comma-separated String object. Here we will pass a comma for the separator parameter and the String Array for the value parameter. The String(separator, value) method returns a String that consists of the elements in value delimited by the separator String or an empty String if provided String Array contains zero elements.

The String Join(string? separator, params string?[] value) method overload throws ArgumentNullException if the value is null. It also throws OutOfMemoryException if the length of the resulting String overflows the maximum allowed length (Int32.MaxValue).

So finally, using this String class Join(String, String[]) method overload the .net c# developers can convert a String Array to a comma-separated String object.
convert-string-array-to-comma-separated-string.aspx

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

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)    
    {  
        string[] birds = new string[]  
        {  
            "Horned Screamer",  
            "Cackling Goose",  
            "Greylag Goose",  
            "Andean Flamingo"
        };  

        Label1.Text = "birds array.........<br />";
        foreach (string s in birds)  
        {  
            Label1.Text += s + "<br />";  
        }

        string commaseparatedstring = String.Join(",", birds);
        Label1.Text += "<br />string array to comma separated string........<br />";
        Label1.Text += commaseparatedstring;
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string array to comma separated string</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:DarkBlue; font-style:italic;">    
            c# example - string array to comma separated string
        </h2>    
        <hr width="550" align="left" color="LightBlue" />      
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"    
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="convert string array to comma separated string"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to convert a string array to a string

Convert a String Array to a String
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a String Array instance to a String object. That means we will get a String instance from the elements of a String Array. Here we will join the String Array elements with a separator and build an instance of the String object. In this .net c# example code, we will use the String class Join() method.

The String Join() method concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

The String Join(String, String[]) method overload concatenates all the elements of a string array, using the specified separator between each element. The Join (string? separator, params string?[] value) method overload has two parameters named separator and value. The separator parameter is the string to use as a separator. The separator is included in the returned string only if the value has more than one element. The value parameter is an Array that contains the elements to concatenate.

So, using this method overload we can join String Array elements to a String object. Here we will pass an empty String for the separator parameter and the String Array for the value parameter. The String(separator, value) method overload returns a string that consists of the elements in value delimited by the separator string or an empty String if provided String Array contains zero elements.

The String Join(string? separator, params string?[] value) method overload throws ArgumentNullException if the value is null. It also throws OutOfMemoryException if the length of the resulting string overflows the maximum allowed length (Int32.MaxValue).

So finally, using this String class Join(String, String[]) method overload the .net c# developers can convert a String Array to a String.
convert-string-array-to-string.aspx

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

<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)    
    {  
        string[] stringarray = new string[]  
        {  
            "how",  
            "are",  
            "you"
        };  

        Label1.Text = "string array.........<br />";  
        foreach (string s in stringarray)  
        {  
            Label1.Text += s + "<br />";  
        }

        string convertedstring = String.Join("", stringarray);
        Label1.Text += "<br />string array to converted string: " + convertedstring;
    }    
</script>    

<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string array to string</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:DarkBlue; font-style:italic;">    
            c# example - string array to string
        </h2>    
        <hr width="550" align="left" color="LightBlue" />      
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"    
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="convert string array to string"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>

c# - How to convert a decimal array to a double array

Convert a Decimal Array to a Double Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a Decimal Array to a Double Array. But there is no direct method to convert a Decimal Array object to a Double Array instance. So, we have to perform some tasks to get a Double Array from Decimal Array elements.

The .net c# developers have to initialize an empty instance of a Double Array at the beginning. While initializing the Double Array instance, we will set the Double Array size exactly the same as the Decimal Array size. Next, we have to loop through the Decimal Array elements. While iterating the Decimal Array elements, we also set the Double Array’s elements value corresponding to the Decimal Array elements.

While setting the Double Array’s elements value .net developers have to convert the Decimal value to Double instance. In this .net example code, we will use the Convert class ToDouble() method to convert a Decimal instance to a Double instance. So finally, we will get a Double Array instance from the Decimal Array elements.

The Convert class converts a base data type to another base data type. The Convert class ToDouble() method converts a specified value to a double-precision floating-point number.

The Convert class ToDouble(Decimal) method overload converts the value of the specified decimal number to an equivalent double-precision floating-point number. The Convert class ToDouble (decimal value) method overload has a parameter named value.

The value parameter is the decimal number to convert. The Convert class ToDouble(Decimal) method returns a double-precision floating-point number that is equivalent to value.
convert-decimal-array-to-double-array.aspx

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

<!DOCTYPE html>  
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        decimal[] decimalarray = new decimal[]
        {
            51.28M,
            12.93M,
            13.50M,
            29.84M,
            8.0M
        };

        Label1.Text = "decimal array.........<br />";
        foreach (decimal d in decimalarray)
        {
            Label1.Text += d.ToString() + "<br />";
        }

        double[] darray = new double[decimalarray.Length];
        for (int i = 0; i < decimalarray.Length;i++ )
        {
            darray[i] = Convert.ToDouble(decimalarray[i]);
        }

        Label1.Text += "<br />converted double array.........<br />";
        foreach (double d in darray)
        {
            Label1.Text += d.ToString() + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - convert decimal array to double array</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - convert decimal array to double array
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    
        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="convert decimal array to double array"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to convert a decimal array to a string array

Convert a Decimal Array to a String Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a Decimal Array to a String Array. But there is no direct method in the Array class to convert a Decimal Array instance to a String Array instance. So, we have to do some tasks to get a String Array from Decimal Array elements.

The .net c# developers have to initialize an empty instance of a String Array at the beginning. While initializing the String Array instance, we will set the String Array size exactly the same as the Decimal Array size. Next, we have to loop through the Decimal Array elements. While iterating the Decimal Array elements, we also set the String Array’s elements value corresponding to the Decimal Array elements.

While setting the String Array’s elements value .net developers have to convert the Decimal value to a String instance. In this .net example code, we will use the Decimal class ToString() method to convert a Decimal instance to a String instance. So finally, we will get a String Array instance from the Decimal Array elements.

The Decimal class ToString() method converts the numeric value of this instance to its equivalent String representation. This method returns a string that represents the value of this instance. The Decimal class ToString() method formats a Decimal value in the default ("G", or general) format of the current culture.
convert-decimal-array-to-string-array.aspx

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

<!DOCTYPE html>  
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        decimal[] decimalarray = new decimal[]
        {
            5.28M,
            2.93M,
            11.5M,
            2.82M,
            9.5M
        };

        Label1.Text = "decimal array.........<br />";
        foreach (decimal d in decimalarray)
        {
            Label1.Text += d.ToString() + "<br />";
        }

        string[] stringarray = new string[decimalarray.Length];
        for (int i = 0; i < decimalarray.Length;i++ )
        {
            stringarray[i] = decimalarray[i].ToString();
            //another way for conversion
            //stringarray[i] = Convert.ToString(decimalarray[i]);
        }

        Label1.Text += "<br />converted string array.........<br />";
        foreach (string s in stringarray)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - decimal array to string array</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - convert decimal array to string array
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="convert decimal array to string array"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to convert a decimal array to a string

Convert a Decimal Array to a String
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a Decimal Array instance to a String object. That means we will get a String object from Decimal Array elements. In this .net code, we will join the Decimal Array elements with a specified separator and build an instance of the String object. Here we will use the String class Join() method.

The String class Join() method concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

The String class Join(String, String[]) method overload concatenates all the elements of a String array, using the specified separator between each element. The Join (string? separator, params string?[] value) method has two parameters those are separator and value. Here the separator parameter is the String to use as a separator. And the value parameter is an Array that contains the elements to concatenate.

So, using this method overload .net developers can join Decimal Array elements to a String instance. Here we will pass “, ” for the separator parameter value and the Decimal Array for the value parameter. The String(separator, value) method returns a String that consists of the elements in value delimited by the separator String or an empty String if our provided Decimal Array contains zero elements.

The String Join(separator, value) method throws ArgumentNullException when the provided value is null. This method also throws OutOfMemoryException if the length of the resulting string overflows the maximum allowed length (Int32.MaxValue).

So finally, using this String class Join(String, String[]) method the .net c# developers can convert a Decimal Array to a String.
convert-decimal-array-to-string.aspx

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

<!DOCTYPE html>  
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        decimal[] decimalarray = new decimal[]
        {
            1.23M,
            2.99m,
            10.0M,
            2.88M,
            4.5M
        };

        Label1.Text = "decimal array.........<br />";
        foreach (decimal d in decimalarray)
        {
            Label1.Text += d.ToString() + "<br />";
        }

        string convertedstring = String.Join(", ", decimalarray);
        Label1.Text += "<br />decimal array to converted string: " + convertedstring;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - convert decimal array to string</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - convert decimal array to string
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="convert decimal array to string"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to convert a string array to an int array

Convert a String Array to an Int Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a String Array to an Int Array. That means we will convert a String Array instance to an Int Array instance where all the elements of the Srting Array are the String representations of int values. But there is no direct method to convert a String Array object to an Int Array instance. So, we have to perform some jobs to get an Int Array from String Array elements.

At first, we have to initialize an empty instance of an Int Array. While initializing the Int Array instance, we will set the Int Array size exactly the same as the String Array size. After that, we will loop through the String Array elements. While iterating the String Array elements, we will set the Int Array’s elements value corresponding to the String Array elements.

While setting the Int Array elements value we have to convert the String value to Int instance. In this .net example code, we will use the Convert class ToInt32() method to convert a String instance to an integer instance. So finally, we will get an Int Array instance from the String Array elements.

The Convert class converts a base data type to another base data type. The Convert class ToInt32() method converts a specified value to a 32-bit signed integer.

The Convert class ToInt32(String) method overload converts the specified string representation of a number to an equivalent 32-bit signed integer. The Convert class ToInt32 (string? value) method overload has a parameter named value.

The value parameter is a string that contains the number to convert. The Convert class ToInt32(String) method returns a 32-bit signed integer that is equivalent to the number in value, or 0 if the value is null.

The Convert class ToInt32(string? value) method overload throws FormatException if the value does not consist of an optional sign followed by a sequence of digits (0 through 9). It also throws OverflowExceptionif the value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.
convert-string-array-to-int-array.aspx

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

<!DOCTYPE html>  
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] stringarray = new string[]
        {
            "100",
            "99",
            "125",
            "122",
            "25"
        };

        Label1.Text = "string array.........<br />";
        foreach (string s in stringarray)
        {
            Label1.Text += s + "<br />";
        }

        int[] intarray = new int[stringarray.Length];
        for (int i = 0; i < stringarray.Length;i++ )
        {
            intarray[i] = Convert.ToInt32(stringarray[i]);
        }

        Label1.Text += "<br />int array.........<br />";
        foreach (double d in intarray)
        {
            Label1.Text += d.ToString() + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - convert string array to int array</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - convert string array to int array
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="convert string array to int array"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to convert a string array to a double array

Convert a String Array to a Double Array
The Array class provides methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespaces. However, it is still considered a collection because it is based on the IList interface. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The Array has a fixed capacity.

The following .net c# tutorial code demonstrates how we can convert a String Array to a Double Array. That means we will convert a String Array instance whose elements are Double data type to a Double Array object. But there is no direct method to convert a String Array instance to a Double Array object. So, we have to apply some actions to get a Double Array from String Array elements.

In the beginning, we have to initialize an empty instance of Double Array. In the initializing time, we will set the Double Array size the same as the String Array size. Then we will loop through the String Array elements. While iterating the String Array elements, we will set the Double Array elements value corresponding to the String Array elements.

But we have to convert the String value to a Double instance. Here we will use the Convert class ToDouble() method to convert a String instance to a Double instance. So finally, we will get a Double Array instance from the String Array elements.

The Convert class converts a base data type to another base data type. The Convert class ToDouble() method converts a specified value to a double-precision floating-point number.

The Convert class ToDouble(String) method overload converts the specified string representation of a number to an equivalent double-precision floating-point number. The Convert class ToDouble (string? value) method overload has a parameter named value.

The value parameter is a string that contains the number to convert. The Convert class ToDouble(String) method returns a double-precision floating-point number that is equivalent to the number in value, or 0 if the provided value is null.

The Convert class ToDouble (string? value) method overload throws FormatException if the value is not a number in a valid format. It also throws OverflowException if the provided value represents a number that is less than Double.MinValue or greater than Double.MaxValue.
convert-string-array-to-double-array.aspx

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

<!DOCTYPE html>  
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] stringarray = new string[]
        {
            "15.56",
            "16.23",
            "55.70",
            "28.89"
        };

        Label1.Text = "string array.........<br />";
        foreach (string s in stringarray)
        {
            Label1.Text += s + "<br />";
        }

        double[] darray = new double[stringarray.Length];
        for (int i = 0; i < stringarray.Length;i++ )
        {
            darray[i] = Convert.ToDouble(stringarray[i]);
        }

        Label1.Text += "<br />double array.........<br />";
        foreach (double d in darray)
        {
            Label1.Text += d.ToString() + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - convert string array to double array</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - convert string array to double array
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="convert string array to double array"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to convert a double array to a string

Convert double array to string
The following asp.net c# example code demonstrate us how can we convert a double array to a string objectprogrammatically at run time in an asp.net application. We can not directly convert a double array to string object.

To convert, a double array to a string value, first we need to convert the double array to string array by convertingeach elements data type double to string. Then we can join the converted string array elements to create a string value.

.Net framework's array object work as like a collection, so we can apply Select method to an array. Using LinqSelect method we select all elements from the double array and convert each element value data type double to string.Finally, we convert the double array to string array by using Linq Select() method and ToArray() method.

Next, we can join each elements of double array to create a new string object. We can use a separator to join array elements.String Class String.Join() method concatenate the elements of a specified array or the members of a collection, using thespecified separator between each element or member.

String.Join(String, String[]) overloaded method concatenate all the elements of a string array, using the specified separatorbetween each element. Here we uses this overloaded method to convert the converted string array to string object. At last, we geta string object which value is converted from a double array and elements are separated by white space.
convert-double-array-to-string.aspx

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

<!DOCTYPE html>  
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        double[] doublearray = new double[]
        {
            15.05,
            10.23,
            55.70,
            29.89
        };

        Label1.Text = "double array.........<br />";
        foreach (double d in doublearray)
        {
            Label1.Text += d.ToString() + "<br />";
        }

        string convertedstring = String.Join(" ", doublearray);
        //another way tto convert double array items to string
        //string convertedstring = String.Join(" ", doublearray.Select(x=>x.ToString()).ToArray());

        Label1.Text += "<br />converted string: " + convertedstring;
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - convert double array to string</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - convert double array to string
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="Large"  
            >  
        </asp:Label>  
        <br /><br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="convert double array to string"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>

c# - How to add a new item in an existing array

Add new item in existing array
The following asp.net c# example code demonstrate us how can we add an item/element to an existingarray programmatically at run time in an asp.net application. .Net framework's array class has no direct built inmethod or property to add or append an element with value to array elements collection.

.Net framework's array object is a fixed size elements collection. so, if we want to add an item to an existingarray object, then fist we need to resize array object to allocate available space for new element. Array.resize() methodallow us to change the number of elements of a one-dimensional array to the specified new size.

To add a new element to an array object we can set array new size as Array.Length+1. Now, the last element of the array isour newly added empty element. We can set a value for this newly added element as this way Array[Array.Length-1]="value".array.Length-1 indicate the last element of an array, because array maintain zero-based index.
add-new-item-in-existing-array.aspx

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

<!DOCTYPE html>  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
    {
        string[] birds = new string[]
        {
            "Pied Monarch",
            "Crested Jay",
            "Blue Jay",
            "European Magpie"
        };

        Label1.Text = "birds array[" + birds.Length.ToString()+ "].........<br />";
        foreach(string s in birds)
        {
            Label1.Text += s + "<br />";
        }

        Array.Resize(ref birds, birds.Length + 1);
        birds[birds.Length - 1] = "House Crow";

        Label1.Text += "<br />after added new item birds array["+ birds.Length.ToString()+"].........<br />";
        foreach (string s in birds)
        {
            Label1.Text += s + "<br />";
        }
    }  
</script>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - add new item in existing array</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:DarkBlue; font-style:italic;">  
            c# example - add new item in existing array
        </h2>  
        <hr width="550" align="left" color="LightBlue" />    

        <asp:Label   
            ID="Label1"   
            runat="server"  
            Font-Size="X-Large"  
            >  
        </asp:Label>  
        <br />
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="add a new item in existing array"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>  
    </form>  
</body>  
</html>