Lookup with generic List and Dict (VB.NET)

When using a Dictionary the key have to be unique. If you want to lookup another property than the key, then you can use ToLookup(), if the property is unique.
http://msdn.microsoft.com/en-us/library/bb549211.aspx

You could also choose to convert the List to a Dict using ToDictionary()

Imports System.Collections.Generic 'List
Imports System.Linq '.NET3.0 extension methods: ToLookup(), ToDictionary()

Public Sub SomeSub()
Dim my1stList As List(Of MyObject) = LoadMyList() 'Get some data

Dim my2ndList As List(Of MyObject)
Dim myDict As Dictionary(Of String, MyObject)
Dim myLookup As ILookup(Of String, MyObject)
Dim myRow As MyObject = Nothing

'Following will crash in runtime if the key field userid on MyObject is not unique

'Example of using lookup with userid as key
myLookup = my1stList.ToLookup(Function(o) o.userid) 'using IEnumerable.ToLookup()
myRow = myLookup.Item("myuserid" )
Console.WriteLine(myRow.someProperty)

'convert the List to a Dict
myDict = my1stList.ToDictionary(Function(o) o.userid, Function(o) o)
'or
myDict = my1stList.ToDictionary(Of MyObject, String)(Function(o) o.userid)
myRow = myDict("myuserid" )
Console.WriteLine(myRow.someProperty)

C#:  

	myDict = my1stList.ToDictionary(p => p.userid, p => p);
	//or
	myDict = my1stList.ToDictionary<MyObject, string>(p => p.userid);
Advertisements

One Comment

Add yours →

  1. Brilliant thanks for the nifty way to create a Dictionary using VB.NET.

    Being a C# dev by heart isn´t always the best on a VB assignment… :-)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: