Lookup<TKey, TElement> 的意义何在? [英] What is the point of Lookup&lt;TKey, TElement&gt;?

查看:36
本文介绍了Lookup<TKey, TElement> 的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN 这样解释查找:

The MSDN explains Lookup like this:

A 查找类似于 Dictionary.不同的是,一个Dictionary 将键映射到单个值,而Lookup 将键映射到值的集合.

A Lookup<TKey, TElement> resembles a Dictionary<TKey, TValue>. The difference is that a Dictionary<TKey, TValue> maps keys to single values, whereas a Lookup<TKey, TElement> maps keys to collections of values.

我不觉得这个解释特别有帮助.查找有什么用?

I don't find that explanation particularly helpful. What is Lookup used for?

推荐答案

它是 IGrouping 和字典之间的交叉.它让您可以通过一个键将项目组合在一起,然后通过该键以一种有效的方式访问它们(而不是仅仅遍历它们,GroupBy 允许您这样做).

It's a cross between an IGrouping and a dictionary. It lets you group items together by a key, but then access them via that key in an efficient manner (rather than just iterating over them all, which is what GroupBy lets you do).

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

For example, you could take a load of .NET types and build a lookup by namespace... then get to all the types in a particular namespace very easily:

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.)

(I'd normally use var for most of these declarations, in normal code.)

这篇关于Lookup<TKey, TElement> 的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆