开发者

collection help please

开发者 https://www.devze.com 2023-03-04 23:00 出处:网络
I have a collecti开发者_运维百科on< of int\'s >. 1 2 3 When i remove, for example, the 2. The collection becomes 1,3.

I have a collecti开发者_运维百科on< of int's >.

1
2
3

When i remove, for example, the 2. The collection becomes 1,3. However, when I go to add another item the list becomes

1
3
3

Because the sequence is based off the count of items in collection

is there an easy way to resequence. The example above where i'm showing 1,3 should be resequence to 1,2 and then the next new item will be a 3.


It sounds like your list can be replaced with a integer variable, since all you are "storing" here is the (1-based) index of the item in the list. Creating a "list" from 1 to n would just be int count = n. Testing if an item is in the list becomes if (item <= count). Adding an item would be count++, and removing count--.


You could rewrite your list every time you remove an object using Enumerable.Range, so the code to you would be something like this:

    //execute this after remove element
void Resequence()
        {
            myList = Enumerable.Range(1, myList.Count).ToList();
        }

so the add will be something like this

void AddElement(){
   myList.Add(myList.Count + 1);
}

Note: in the add element you should remove the +1 if the list is zeroBased.

0

精彩评论

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