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