2012-06-12 195 views
0

到一个列表转换为字典,我们可以与follwing轻松地做到这一点:Lambda表达式

list.ToDictionary(v=> v, v=>true); 

对于第一个参数在ToDictionary,我能理解的第一个参数是词典的元素。但是v=> true是什么意思?

第二个参数应该是IEqualityComparer类型。这有什么用途? v=> true如何与IEqualityComparer相同?

回答

1

This是使用的方法。

第二个参数(V =>真)为elementSelector变换函数以从每个元件产生结果元素值)。

与元件123将导致与下面的映射的字典列表(所有值都true):

1: true 
2: true 
3: true 
+0

或英文此方法;-) http://msdn.microsoft.com/en-us/library/bb548657.aspx –

+0

@MA fifi谢谢,修正:-)黎明你,谷歌! – sloth

+0

字典正如其名称所暗示的_dictionary_,它用于使用键查找值。如果你没有,也不需要价值,你可能会更好使用HashSet executor

1

当您的列表具有[1,2,3,4]并且将其转换为一本词典list.ToDictionary(v=> v, v=>true);那么你的字典里有这个值

[1,true] 
[2,true] 
[3,true] 
[4,true]. 

的第一个值是关键,第二是价值

编辑:

正如@dkson所述第二参数是elementSelector。你可以在intellisense中看到这一点,当你去4条的第3条:)

+0

是的,但Intellisense显示ToDcitionary中的secodn元素必须是“IEqualityComparer” – user1240679

+0

智能感知可能是错误的 –

1

你看看​​。这是超载采取第二IEqualityComparer参数:

ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IEqualityComparer<TKey>) 

然而,在你的榜样,你正在使用,这需要Func<TSource, TElement>负责生成值的字典过载:

ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>) 

(在你的情况,所有值都只是true