【发布时间】:2010-10-14 16:53:16
【问题描述】:
我正在使用 Microsoft .NET Framework 4.0。
我在Dictionary<T, List<T>> 上使用聚合来提取字典中所有类型List<T> 列表中使用的T 类型值集。这是我能想到的最简单的情况,它表现出相同的行为。
首先,正如documentation 所述,以下确实有效:
var set = new HashSet<int>();
var list = new LinkedList<int>();
var newSet = set.Union(list);
也就是说,我可以在HashSet 上调用Union,并以List 作为参数(因为它实现了IEnumerable)。
然而,LINQ Aggregate 表达式的 Func 参数中的等效表达式会产生错误(至少是预编译器):
new List<int>[] { new List<int>() }.Aggregate(new HashSet<int>(), (acc, list) => acc.Union(list));
它期望 Union 的参数是 HashSet,如果给它一个参数,它就会合作,这与它在 LINQ/Func 表达式之外的行为相反。
我遇到问题时使用的真实示例是:
public AdjacencyListGraph(Dictionary<TVertex, LinkedList<TVertex>> adjacencyList)
{
var vertices = adjacencyList.Aggregate(new HashSet<TVertex>(),
(vertices, list) => vertices.Union(list.Value));
}
抱怨它无法将IEnumerable<TVertex> 转换为HashSet<TVertex>...
【问题讨论】:
-
我很好奇,“预编译器”是什么意思?
标签: linq c#-4.0 union aggregate hashset