Calvin
Calvin

Reputation: 641

how to remove first item from list and keep index

I have a list and want to remove the first item while keeping the index of the next the same. For example:

public List<string> Fruit
{
    get
    {
        List<string> fruits = dataSource.GetFruits();

        return messageStatuses ;
    }
}

result returned

[0] -- apple
[1] -- grape
[2] -- orange
[3] -- peach

when the first item is remove the result should be:

[1] -- grape
[2] -- orange
[3] -- peach

Upvotes: 5

Views: 13561

Answers (4)

Adil
Adil

Reputation: 148110

You can use dictionary for this

Dictionary<int,string> dic = new Dictionary<int,string>();

dic.Add(0,"Apple");
dic.Add(1,"Grape");
dic.Add(2,"Orange");
dic.Add(3,"Peach");

dic.Remove(0);

Now dic[1] will give you "Grape"

Upvotes: 7

Servy
Servy

Reputation: 203821

Just set the item at index 0 to null, or some other value to indicate that it was removed. Obviously for value types (i.e. int) this may not be a feasible option. It will also result in the Count including all of the null values, which may or may not be desirable.

Upvotes: 2

KyorCode
KyorCode

Reputation: 1497

Work with an array instead of a list. This will allow for you to remove items at certain indexes, without messing up the indexing itself.

Upvotes: 1

Wesley
Wesley

Reputation: 5621

Lists in C# don't function like a JavaScript array, where you can remove an item and leave undefined in it's place.

You need to replace your value with a placeholder you can ignore. Something like

Fruit[0] = "ignore";

and then deal with that in your loops.

Upvotes: 0

Related Questions