如何从列表中"出列"元素?

Mc'*_*ips 48 c# arrays

我有一张名为_deck的卡片列表:

 private List<String> _deck = new List<String> {"2h", "3h", "4h", ... }
Run Code Online (Sandbox Code Playgroud)

然后我想从列表中删除一张卡并保存到变量中.我正在尝试:

 String p1FirstCard = _deck.RemoveAt(0);
Run Code Online (Sandbox Code Playgroud)

但我收到错误"无法将类型void转换为String".

在C#List中有类似push/pop的东西,但是在List的"head"或"start"处是这样的吗?(推/弹工作在列表的"尾部"或"结尾".)

如果没有,我应该如何删除第一个元素但将其保存在变量中?

Fre*_*dou 46

你能简单地使用c#已经拥有的Queue类吗?

class Program
{
    static void Main(string[] args)
    {
        var _deck = new Queue<String>();
        _deck.Enqueue("2h");
        _deck.Enqueue("3h");
        _deck.Enqueue("4h");
        _deck.Enqueue("...");

        var first = _deck.Dequeue(); // 2h
        first = _deck.Dequeue(); // 3h
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以简单地使用c#已经拥有的Stack类

class Program
{
    static void Main(string[] args)
    {
        var _deck = new Stack<String>();
        _deck.Push("2h");
        _deck.Push("3h");
        _deck.Push("4h");
        _deck.Push("...");

        var first = _deck.Pop(); // ...
        first = _deck.Pop(); // 4h
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Pop 和 Dequeue 确实从列表末尾删除。请参阅此处:https://msdn.microsoft.com/en-us/library/system.collections.stack.pop(v=vs.110).aspx 或此处 https://msdn.microsoft.com/en-us /library/1c8bzx97(v=vs.110).aspx (2认同)

Ale*_*exD 43

您可以分两步完成:

String p1FirstCard = _deck[0];
_deck.RemoveAt(0);
Run Code Online (Sandbox Code Playgroud)

您可以编写自己的扩展帮助方法(我添加了一个索引Pop,如@Fredou建议:

static class ListExtension
{
    public static T PopAt<T>(this List<T> list, int index)
    {
        T r = list[index];
        list.RemoveAt(index);
        return r;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后打电话

String p1FirstCard = _deck.PopAt(0);
Run Code Online (Sandbox Code Playgroud)

PS 这个名字可能有点令人困惑. Pop通常删除最后一个元素,而不是第一个元素.


ora*_*rad 6

在AlexD 的回答的基础上,我添加了更多扩展方法:

public static class ListExtensionMethods
{
    public static T PopAt<T>(this List<T> list, int index)
    {
        var r = list[index];
        list.RemoveAt(index);
        return r;
    }

    public static T PopFirst<T>(this List<T> list, Predicate<T> predicate)
    {
        var index = list.FindIndex(predicate);
        var r = list[index];
        list.RemoveAt(index);
        return r;
    }

    public static T PopFirstOrDefault<T>(this List<T> list, Predicate<T> predicate) where T : class
    {
        var index = list.FindIndex(predicate);
        if (index > -1)
        {
            var r = list[index];
            list.RemoveAt(index);
            return r;
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)