ToLookup, LINQ and Index
I have the following situation (VB.NET, .NET 4):
Generic list of custom objects letters(Of Letter)
A, B, C, B, D
need a collection containing items and its indexes:
A (0)
B (1, 3)
C (2)
D (4)
Some tries:
Dim letters As New List(Of Letter)
Dim query As ??? = letters.Select(Function(letter, index) _
New With {index, letter})
Dim lookup As Lookup(Of Letter, Intege开发者_StackOverflow中文版r)
lookup = letters (query).ToLookup(???
First use the overload of Select
that supports an index to create a tuple(or KeyValuePair
) of letter and index. Then use the overload of ToLookUp
that takes selectors for both key and value.
You might need to either supply an IEqualityComparer<Letter>
to ToLookUp
, or override both Letter.Equals
and Letter.GetHashCode()
. Those two need to be overridden together so they are consistent, or you'll get wrong results.
Dim lookup = Enumerable.Range(0, letters.Count).ToLookup(Function(i) letters(i))
精彩评论