小编典典

查找的目的是什么?

c#

MSDN这样解释查找:

A Lookup<TKey, TElement> 类似于Dictionary<TKey, TValue>。区别在于
Dictionary 将键映射到单个值,而 Lookup 将键映射到值的集合。

我认为这种解释没有特别的帮助。查找的用途是什么?


阅读 572

收藏
2020-05-19

共1个答案

小编典典

这是an
IGrouping和字典之间的交叉。它使您可以通过键将项目分组在一起,然后以一种有效的方式通过该键访问它们(而不仅仅是遍历它们,这就是GroupBy您要做的事情)。

例如,您可以加载.NET类型并按名称空间构建查找…,然后非常轻松地获取特定名称空间中的所有类型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

public class Test
{
    static void Main()
    {
        // Just types covering some different assemblies
        Type[] sampleTypes = new[] { typeof(List<>), typeof(string), 
                                     typeof(Enumerable), typeof(XmlReader) };

        // All the types in those assemblies
        IEnumerable<Type> allTypes = sampleTypes.Select(t => t.Assembly)
                                               .SelectMany(a => a.GetTypes());

        // Grouped by namespace, but indexable
        ILookup<string, Type> lookup = allTypes.ToLookup(t => t.Namespace);

        foreach (Type type in lookup["System"])
        {
            Console.WriteLine("{0}: {1}", 
                              type.FullName, type.Assembly.GetName().Name);
        }
    }
}

(我通常会var在普通代码中使用大多数这些声明。)

2020-05-19