:::: MENU ::::

Monday, January 19, 2009

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 squiggly line

http://sqlblogcasts.com/Photos/blogimages/images/11198/480x480.aspx

"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'."

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 myself, but it’s a lot easier. What’s 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.