从列表中删除并返回第一个项目

13

我想知道是否有一种内置方法可以使用一个方法/命令删除并返回列表的第一个项目。

我使用了这个,但它不太美观。

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

所以我可以写一个扩展方法:

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();

这是最好的选择吗?还是有内置方法可用?
该列表来自 nHibernate-Query,因此它应该保持为 List<T>

1
“不太美观”和“最佳可能性”使得这个问题更多基于个人意见。.NET不像PHP那样为每两个语句的组合引入一个函数。你实际的问题是什么?是否这个特定的方法被构建到了List<T>中或者作为扩展方法可用?如果是,那么答案是否定的。 - CodeCaster
2个回答

15

这个操作最适合使用的集合是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)

队列让入队(Enqueue)出队(Dequeue)操作非常快。但是,如果您需要在队列内搜索,或按索引获取项目,则这是一个不好的选择。请根据您需要执行的操作类型选择最合适的集合——队列、堆栈、列表或简单数组。

此外,您可以从列表(List)创建一个队列(Queue)

var list = new List<int>();
var queue = new Queue<int>(list);

2
如果唯一的要求是“我想要一个通用集合来存储和检索先进先出的对象”,那么…… - CodeCaster
@CodeCaster 是的,当然了,我添加了一些解释 - Backs
如果你想让一个列表像“删除第一个项目并返回它”的行为,那么你需要的是一个队列。 - mehmet mecek
2
@mecek 绝对不是这样的。它是为列表添加了一个开箱即用中没有的功能。如果这是唯一的要求,那么 Queue<T> 可能是更好的选择。但是,如果 OP 仍然希望能够索引到集合中或者能够从除第一个索引以外的其他索引中删除项目,则 List<T> 仍然是更好的选择。 - CodeCaster

7

没有内置方法。我认为你的代码很好。

有一点小问题,我会使用索引器而不是First扩展方法:

T currentFirst = list[0];

检查您的列表是否存在Count > 0

public static T RemoveAndReturnFirst<T>(this List<T> list)
{
    if (list == null || list.Count == 0)
    {
        // Instead of returning the default,
        // an exception might be more compliant to the method signature.

        return default(T);
    }

    T currentFirst = list[0];
    list.RemoveAt(0);
    return currentFirst;
}

如果你需要考虑并发性,我建议使用另一种集合类型,因为这个不是线程安全的。

你的代码看起来像是 RemoveAndReturnFirstOrDefault 方法。 - Vadim Martynov
1
实际上,使用异常而不是default(T)也是一种可能性,甚至可能更好 :)。 - Patrick Hofman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接