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
"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
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.
MatchedUsers = (from MembershipUser u in Membership.FindUsersByEmail("SomeEmail")
where u.UserName != "Smith"
&& u.CreationDate > DateTime.Now.AddDays(-1)
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