Search

Tuesday, March 25, 2014
0 comments

Remove last element of array in C#

8:58 PMTuesday, March 25, 2014
Using the Resize method you can decrement size of an array. Resize method creates a new array with new specified size Also copy old array items into newly created. Let's take an simple example to remove last element. Take less than one size of original array size. Newly created array skip last element of original array size.

<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Height="37px" onclick="Button1_Click"
        Text="Vegetable" Width="100px" />
    <div>
 
        <asp:Label ID="Label1" runat="server" Text="Label" Width="100px" ForeColor="Black" BackColor="Yellow"></asp:Label>
 
    </div>
    </form>

Business Logic code

 protected void Button1_Click(object sender, EventArgs e)
    {
        string[] Vegtables = new string[]
        {
            "1.Tomato",
            "2.Sweet-potato",
            "3.Onion",
            "4.Potato",
            "5.Carrot",
            "6.Locky",
            "7.Brinjal"
        };

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

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

        Label1.Text += "<br />Vegtables array [last element remove...<br />";
        foreach (string Vegtable in Vegtables)
        {
            Label1.Text += Vegtable + "<br />";
        }
    }

Code Generate the following Output


Resize array method
Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top