Sunday, July 14, 2013

Selecting Items from a Collection using Another Collection with LINQ Joins

Here's the problem: you have a collection of objects with lots of information in those objects (the "rich" objects). You also have a collection of objects that represent a selection your user made in your application's UI (the "selected" objects). Unfortunately, your "selected" collection is a different and less useful set of objects; you really want to work with the "rich" objects. So Your problem is finding all the matching objects from the "rich" collection, based on the objects in the "selected" collection.

A LINQ Join solves the problem. Joining the two collections together gives you a new collection of the "rich" objects that have a matching item in the "selected" collection. In the LINQ statement's Join/On clause, you just need to specify the properties to be used to join the two collections together.

The following code joins an Entity Framework collection of all of the users in the company (CompanyUsers -- the rich objects) with a group of selected users from the UI (SelectedUsers -- the selected objects). The resulting collection holds just the rich objects:

Dim usrs = From cu In context.CompanyUsers
           Join id In SelectedUsers On cu.ID Equals id
           Select cu

QR: Inline image 1