Using LINQ with unfriendly collections

I've liked the idea of LINQ in that you can query in memory collections. It saves a huge amount of code if you want to filter users by other criteria.

I'd seen demos and just couldn't figure out how it worked because I was just getting a red suiggly line

"Error 2 Could not find an implementation of the query pattern for source type 'System.Web.Security.MembershipUserCollection'.  'Where' not found.  Consider explicitly specifying the type of the range variable 'u'."

Now sometimes you just have a mental block but I couldn't figure out what I needed to do to get it working, and I'm sure some onf you reading will be in "Who wants to be a millionaire" mode and will be telling me exactly what the answer is, its obvious.

Well I'm sure I tried what is the correct solution but to no avail.

Anyway I needed to do this again recently and rather than resort to a for loop and a break statement etc I persevered, and soon realised on reading the error message and taking my time was that a simple LINQ query has implied types, i..e in my example the variable "u" (the range variable) is type based on the items in the collection on the right just like var does. However in this case it can't infer the type and so you have to force the type i.e.

var MatchedUsers = (from MembershipUser u in Membership.FindUsersByEmail("SomeEmail")

                    where u.UserName != "Smith"

                    && u.CreationDate > DateTime.Now.AddDays(-1)

                    select u);

Now I'm sure this might not be as quick as doing the looping my self, but its a lot easier. Whats more if we want to do something else with this set of users we can do easily rather than having to loop over the whole collection again.


-
Published 15 January 2009 14:18 by simonsabin
Filed under: , ,

Comments

# Dew Drop – January 17, 2009 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop – January 17, 2009 | Alvin Ashcraft's Morning Dew

23 January 2009 13:43 by DotNetShoutout

# Using LINQ with unfriendly collections - SimonS Blog on SQL Server Stuff

Thank you for submitting this cool story - Trackback from DotNetShoutout