Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove and Return First Item of List

Tags:

c#

list

I was wondering if there was a build in method to remove and return the first item of a list with one method/command.

I used this, which was not pretty

Item currentItem = items.First();
items.RemoveAt(0);

So I could wrote an extension-method:

public static class ListExtensions
{
    public static T RemoveAndReturnFirst<T>(this List<T> list)
    {
        T currentFirst = list.First();
        list.RemoveAt(0);
        return currentFirst;
    }
 }

//Example code
Item currentItem = items.RemoveAndReturnFirst();

Is this the best possibility or is there any built-in method?

The list is returned from a nHibernate-Query and therefore it should remain a List<T>.

like image 233
JDurstberger Avatar asked Dec 21 '15 15:12

JDurstberger


1 Answers

Most suitable collection for this operation is Queue:

var queue = new Queue<int>();
queue.Enqueue(10); //add first
queue.Enqueue(20); //add to the end

var first = queue.Dequeue(); //removes first and returns it (10)

Queue makes Enqueue and Dequeue operations very fast. But, if you need to search inside queue, or get item by index - it's bad choice. Compare, how many different types of operations do you have and according to this choose the most suitable collection - queue, stack, list or simple array.

Also you can create a Queue from a List:

var list = new List<int>();
var queue = new Queue<int>(list);
like image 168
Backs Avatar answered Sep 21 '22 17:09

Backs