Geeks With Blogs
Fringe SharePoint Continued

I just love Linq in SharePoint. I think it is just an awesome way to write quick queries and get at data quite quickly. I've been working with it for a while on several projects and have been seeing some quirky things with it.

 First, the one problem that has been blogged about the most is that linq does with SPSite and SPWeb objects do not get properly disposed after they are used. You can google around for these issues and fixes. I implemented extension methods that properly disposed of the SPSite and Spweb objects that are created by Linq.


 Secondly, I just noticed this and thought it was interesting. I have been wroking with Property bags on SharePoint objects. Adding key, value pairs to document libraries, sites and folders to act as metadata. I have this line of code:

 var result =myweb.Lists.OfType<SPList>().First(
                        x => x.RootFolder.Properties.ContainsKey("ID") && x.RootFolder.Properties["ID"].Equals("25"));


The intersting thing about this is that if the linq query does not find a match at all, it will actually throw an exception! The exact error is, "Sequense contains no matching element". I was surprized when I saw this. I was under the impression that it would return null.

There is another method you can use:

 var result =myweb.Lists.OfType<SPList>().FirstOrDefault(
                        x => x.RootFolder.Properties.ContainsKey("ID") && x.RootFolder.Properties["ID"].Equals("25"));

This will return the first element that matches the predicate or NULL if it is not found. This was the result I expected from the first line of code. Oh well, just interesting and thought I'd write a quick note about it.



Posted on Monday, November 30, 2009 5:13 PM SharePoint | Back to top

Comments on this post: Linq in SharePoint Interesting Result

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © juanlarios | Powered by: