开发者

How delete an item from struct array in C#

I have a struct in C# and I define and array list of my struct based on my code that I express here. I add items in my array list, but I need to delete a few rows from my list 开发者_JAVA百科too. Could you help me how can I delete item or items from my struct array list:

public struct SwitchList
    {
        public int m_Value1, m_Value2;
        public int mValue1
        {
            get  { return m_Value1;  }
            set  {m_Value1 = value; }
        }

        public int mValue2
        {
            get  { return m_Value2;  }
            set  {m_Value2 = value; }
        }       
   }

   //Define an array list of struct
   SwitchList[] mSwitch = new SwitchList[10]; 

   mSwitch[0].mValue1=1;
   mSwitch[0].mValue2=2;

   mSwitch[1].mValue1=3;
   mSwitch[1].mValue2=4;

   mSwitch[2].mValue1=5;
   mSwitch[2].mValue2=6;

Now how can I delete one of my items, for example item 1. Thank you.


Arrays are fixed length data structures.

You will need to create a new array, sized one less than the original and copy all items to it except the one you want to delete and start using the new array instead of the original.

Why not use a List<T> instead? It is a dynamic structure that lets you add and remove items.


You will need to move elements around and resize the array (which is expensive), since there is some complexity there you going to want to hide it in class that just presents the collection without exposing the implementation details of how its stored. Fortunately Microsoft has already provided a class that does just this called List<T> which along with a few other collection types in System.Collections.Generic namespace meet most common collection needs.

as a side note, you should use auto-properties instead of the trivial property style that you ha


That's not possible, because an array is a fixed size block of elements. Because structs are values types and not reference types, you also can't just set the element zo null. One option would be to create a new smaller array and to copy your remaining values to the new array. But the better approach would be to use a List in my opinion.


If you really, really want to use arrays and move things around, here are some examples of how to do it:

{
    // Remove first element from mSwitch using a for loop.
    var newSwitch = new SwitchList[mSwitch.Length - 1];
    for (int i = 1; i < mSwitch.Length; i++)
        newSwitch[i - 1] = mSwitch[i];
    mSwitch = newSwitch;
}
{
    // Remove first element from mSwitch using Array.Copy.
    var newSwitch = new SwitchList[mSwitch.Length - 1];
    Array.Copy(mSwitch, 1, newSwitch, 0, mSwitch.Length - 1);
    mSwitch = newSwitch;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜