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=3.5.0.0, 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 -->

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




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
Response.Write(items.Count);

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




References:

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:

Google