Search

Friday, March 28, 2014
0 comments

Remove first element from array , Example of List and Resize method

5:41 AMFriday, March 28, 2014

Introduction

If you want to remove first element from an array. First of all, fill array with some values.Create a list collection and fill it with array list. Remove first element using RemoveAt(0) method , here 0 is the first index of array. After remove, must resize array using Resize( )  method. Again pass resized list into array.

Source Code

    <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Animal" Width="100px"
        onclick="Button1_Click" ForeColor="Red" />
    <div>
   
        <asp:Label ID="Label1" runat="server" Text="Label" BackColor="Yellow"
            BorderStyle="Solid" Font-Underline="True" ForeColor="Blue"></asp:Label>
   
    </div>
    </form>

CodeBehind Code

#region remove_first_index
    protected void Button1_Click(object sender, EventArgs e)
    {
        string[] animal = new string[]
        {
            "Cow",
            "Monkey",
            "Black buffalo",
            "Donkey",
            "Yak"
        };

        Label1.Text = "animal array.........<br />";
        foreach (string s in animal)
        {
            Label1.Text += s + "<br />";
        }
        List<string> animallist = animal.ToList();
        animallist.RemoveAt(0);

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

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


        foreach (string s in animal)
        {
            Label1.Text += s + "<br />";
        }
    }
    #endregion

Code Generate the following output

Remove first element from array , Example of List and Resize method
Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top