索引检索和键控检索有什么区别

Whats the difference between indexed retrieval and keyed retrieval

查看 KeyedCollection 的文档,我阅读了以下内容::

The KeyedCollection class provides both O(1) indexed retrieval and keyed retrieval that approaches O(1).

https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.keyedcollection-2?view=netcore-3.1

我不太明白这是什么意思。我个人认为索引检索和键控检索是相同的,因为字典是按键索引的。我觉得 'indexed retrieval' 和 'keyed retrieval' 这两个词我觉得有点含糊。

那有什么区别,为什么肤色不一样?

补充信息: 我个人更愿意使用keyedCollection,因为我有一个列表,将被添加到很多。有时我需要通过 id 获取项目 - Guid 和 return 一些数据。我也会定期浏览列表并删除我不再使用的任何项目。

样本;

    /// <summary>
    /// A collection of leases. Implements <see cref="KeyedCollection{TKey,TItem}"/> which is a dictionary-list hybrid.
    /// </summary>
    public class LeaseInfoCollection : KeyedCollection<Guid, LeaseInfo>
    {
        #region Construction and Destruction

        /// <inheritdoc />
        public LeaseInfoCollection()
        {
        }

        /// <inheritdoc />
        public LeaseInfoCollection(IEqualityComparer<Guid> comparer)
            : base(comparer)
        {
        }

        /// <inheritdoc />
        public LeaseInfoCollection(IEqualityComparer<Guid> comparer, int dictionaryCreationThreshold)
            : base(comparer, dictionaryCreationThreshold)
        {
        }

        #endregion

        #region Overrides of KeyedCollection<string,LeaseInfo>

        /// <inheritdoc />
        protected override Guid GetKeyForItem(LeaseInfo item)
        {
            return item.LeaseId;
        }

        #endregion
    }

这个问题的答案在documentation的下一段:

The KeyedCollection<TKey,TItem> class is a hybrid between a collection based on the IList<T> generic interface and a collection based on the IDictionary<TKey,TValue> generic interface. Like collections based on the IList<T> generic interface, KeyedCollection<TKey,TItem> is an indexed list of items. Like collections based on the IDictionary<TKey,TValue> generic interface, KeyedCollection<TKey,TItem> has a key associated with each element.

从这一段我们可以了解到,我们可以使用序号索引或键访问 KeyedCollection 集合的元素。

这里有一个示例(基于 MSDN 中的示例)展示了这两种检索 KeyedCollection 元素的方法:

public class OrderItem
{
    public OrderItem(string partNumber) => PartNumber = partNumber;

    public string PartNumber { get; }
}

// Custom KeyedCollection.
public class SimpleOrder : KeyedCollection<string, OrderItem>
{
    // Here we define how to get Key from Item for our custom KeyedCollection.
    protected override string GetKeyForItem(OrderItem item) => item.PartNumber;
}

internal static class Program
{
    private static void Main()
    {
        KeyedCollection<string, OrderItem> kc = new SimpleOrder();

        kc.Add(new OrderItem("#0"));
        kc.Add(new OrderItem("#1"));

        // Retrieve item by index.
        Console.WriteLine(kc[0].PartNumber);

        // Retrieve item by key.
        Console.WriteLine(kc["#1"].PartNumber);
    }
}