Wednesday, June 10, 2009

How to use LINQ in SharePoint

LINQ : Language Integrated Query

If you are writing in-line server code (C# and HTML code in same ASPX file), then you have to follow next 2 steps:

1) Page level directive

<%@ Assembly Name="System.Core, Version=, Culture=neutral,
PublicKeyToken=B77A5C561934E089" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Collections.Generic" %>

2) Modify application's web.config file
Add following lines just below </system.Web> node

</system.web><!-- Reference point -->

<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=,
Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System,
Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>

3) LINQ code

If you writing C# in seperate file (Code-behind) then you can skip first two steps.

SPList oList;
//To get a particular SPView specific SPListItems
SPView spView = oList.Views["MySPView_Name"];
SPListItemCollection itemCollec = oList.GetItems(spView);

if (itemCollec != null)
//You can also run following query directly
//over SPList (by replacing itemColle with oList)
List<SPListItem> items
= (from spLItem in itemCollec.OfType<SPListItem>()
where spLItem["Employee Name"] != null
&& Convert.ToString(spLItem["Employee Name"]) == "Avi"
select spLItem).ToList<SPListItem>();

//Write total items count

//To get individual SPListItem you can either use
//Foreach iteration or indexer e.g. items[i]


1) SharePoint Development with LINQ
2) Use Linq inside ...
3) Using LINQ to query a SharePoint List
4) Linq in Sharepoint and querying listitems

No comments: