ATongNa

导航

 

在 C# 中,标准的 Dictionary<TKey, TValue> 不保留元素的插入顺序。要删除最先添加的元素,你需要使用一个同时跟踪插入顺序的数据结构。以下是两种解决思路:

方法 1:使用 LinkedList + Dictionary

public class OrderedDictionary<TKey, TValue>
{
    private readonly LinkedList<TKey> _insertionOrder = new LinkedList<TKey>();
    private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();

    public void Add(TKey key, TValue value)
    {
        _dictionary.Add(key, value);
        _insertionOrder.AddLast(key);
    }

    public bool RemoveFirst(out TKey key, out TValue value)
    {
        if (_insertionOrder.First == null)
        {
            key = default;
            value = default;
            return false;
        }

        key = _insertionOrder.First.Value;
        value = _dictionary[key];
        
        _dictionary.Remove(key);
        _insertionOrder.RemoveFirst();
        return true;
    }

    // 其他方法根据需要实现(如索引器、ContainsKey等)
}
// 使用示例:
var orderedDict = new OrderedDictionary<int, string>();
orderedDict.Add(1, "First");
orderedDict.Add(2, "Second");

if (orderedDict.RemoveFirst(out var firstKey, out var firstValue))
{
    Console.WriteLine($"Removed first: Key={firstKey}, Value={firstValue}");
}

方法 2:使用第三方库

// 安装 NuGet 包:System.Collections.Immutable
using System.Collections.Immutable;

var builder = ImmutableDictionary.CreateBuilder<string, string>();
builder.Add("key1", "First");
builder.Add("key2", "Second");

var immutableDict = builder.ToImmutable();
var firstKey = immutableDict.Keys.First();

// 删除第一个元素
var newDict = immutableDict.Remove(firstKey);
posted on 2025-07-24 10:23  怎么这么难推  阅读(8)  评论(0)    收藏  举报