开发者

How to remove selected array values in C#

Let's consider an array & it's values are

int[] array = {0, 0, 1, -1, -1,-1, 1, 1, 1};

I want 开发者_如何学运维to remove first three values of the array...?

& my result should be array = {-1, -1, -1, 1, 1, 1}

Thanks in advance....!


You can't remove items from an array - it has a fixed size.

However, you could create a new array with only the values you want. With LINQ that's easy:

int[] newArray = array.Skip(3).ToArray();

If you want to modify an existing collection to add or remove values, you want List<T> instead and its RemoveRange method:

List<int> list = new List<int> {0, 0, 1, -1, -1,-1, 1, 1, 1};
list.RemoveRange(0, 3);


You can't resize an array, so you need to create a new one. You could use array.Skip(3).ToArray() for that.


You can use a simple linq function to skip the first records.

int[] array = { 0, 0, 1, -1, -1, -1, 1, 1, 1 };
int[] array2 = array.Skip(3).ToArray();


If you've got Linq handy you can do:

array = array.Skip(3).ToArray<int>();


this is a solution from list approach to your problem.. i know this is little bit long but i think for people who getting started with C# generics must know this kinda stuff too..

add a button to your win-form then double click it and paste this code the hit F5 or run button

        // define array or use your existing array
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        // lets check the number of elements in array first
        MessageBox.Show("Array has " + array.Length.ToString() + " elements only");
        // creating list
        List<int> myList = new List<int>();
        // assigning array to list
        myList = array.ToList();

        // removing first 2 values from list
        // first argument is the index where first item should remove 
        // second argument is how many items should remove
        myList.RemoveRange(0, 3);

        // testing our list
        MessageBox.Show("List count is: "+ myList.Count.ToString());
        string firstItem = myList[0].ToString();
        MessageBox.Show("First Item if the list is :"+firstItem)

        // now if you want you can convert MyList in to array again
        array = myList.ToArray();

        // if you debug and see you will see now the number of elements in array is 7
        MessageBox.Show("New Array has " + array.Length.ToString() + " elements only");

                     ***Best Regards and Happy Programming*** 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜