1

I have a list like this:

public List<ProjectHistoryModel> ProjectHistoryModel = new List<ProjectHistoryModel>();

Now I have Enqueue and Dequeue method like:

private void Enqueue(ProjectHistoryModel model)
{
    ProjectHistoryModel.Add(model);
}

private void Dequeue(List<ProjectHistoryModel> model)
{
    model.RemoveAt(4);
}

It add and remove items correctly except for one reason, when I add new item I want always add it to index [0], for example if I have a list with indexes 0,1,2,3,4,5 and new item comes I have a validation if (ProjectHistoryModel.Count == 5) so dequeue runs and remove index 5 now Enqueue method runs and add new item, but it added as index 5, I want to add it as index 0 and go throught all the others. How can I achieve that?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Juan Pedro
  • 175
  • 9
  • 1
    If you want a queue then use a [`Queue`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1?view=netframework-4.7.2) not a `List`. – DavidG Oct 10 '18 at 17:58
  • I use a Queue and this occurs: `https://stackoverflow.com/questions/52730342/remove-last-item-of-stack?noredirect=1#comment92386809_52730342` @DavidG – Juan Pedro Oct 10 '18 at 18:06
  • Because that's a `Stack`, not a `Queue`. Use the `Enqueue` and `Dequeue` methods. – DavidG Oct 10 '18 at 18:07

1 Answers1

2

To add the item to the zero index use .Insert instead of .Add:

ProjectHistoryModel.Insert(0,model);

As you've experienced, .Add adds the item at the end of the list whereas for .Insert you specify the index to insert the item at. In your case, 0.


Based on @DavidG's comment, unless it is for practice then it is probably better for your needs to use Queue<T> instead of a list.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • I use a Queue and this occurs: `https://stackoverflow.com/questions/52730342/remove-last-item-of-stack?noredirect=1#comment92386809_52730342` @DavidG – Juan Pedro Oct 10 '18 at 18:07