索引检索和键检索之间有什么区别

问题描述 投票:0回答:1

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

KeyedCollection类提供O(1)索引检索和接近O(1)的键检索。

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

我不完全理解这意味着什么。我个人认为索引检索和键检索是相同的,因为字典是通过键索引的。我对“索引检索”和“键检索”这两个词一共感到有些模糊。

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

附加信息:我个人想使用keyedCollection,因为我有一个要添加的列表。我不时需要通过id提取项目-Guid并返回一些数据。我也会定期浏览该列表并删除不再使用的所有项目。

c# list collections complexity-theory
1个回答
0
投票

此问题的答案在documentation的下一段中:

KeyedCollection<TKey,TItem>类是集合之间的混合体基于IList<T>通用接口和基于IDictionary<TKey,TValue>通用接口。像是基于的收藏IList<T>通用接口,KeyedCollection<TKey,TItem>是索引的项目列表。像基于IDictionary<TKey,TValue>通用接口,KeyedCollection<TKey,TItem>具有与每个元素关联的键。

从本段中,我们了解到我们可以使用它们的序号索引或键来访问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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.