Tag Archives: LINQ To SharePoint

Group By SPListItem in SharePoint ListItemCollection

The CAML Query does not support group by object collection. The other workaround is to get the object and group by LINQ query

try
{
using (SPSite oSiteCollection = new SPSite(webUrl))
{
using (SPWeb oWebsite = oSiteCollection.OpenWeb())
{
SPList listName = oWebsite.Lists.TryGetList("MCS");
if (listName != null)
{
SPView myView = listName.Views["GroupBy"];
if (myView != null)
{
SPQuery qry = new SPQuery(myView);
SPListItemCollection myItemsList = listName.GetItems(qry);
var results = (from SPListItem item in myItemsList
group item by item["Group Number"]
into grp
select new
{
GroupID = grp.Key.ToString(),
ListItemsData = grp
});
foreach (var listData in results)
{
MessageBox.Show(listData.GroupID);
foreach (var item in listData.ListItemsData)
{
MessageBox.Show(item["XmlText"].ToString());
}
}
}
}
}

}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

LINQ Query to SharePoint List using Contains with Array

SPMetal tool folder location

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\

Command to create a Entity class for the site

SPMetal /web:http://<servername>/site /namespace:<namesp> /code:filename.cs

ex: SPMetal /web:http://senthamil/sites/sample /namespace:Sample /code:Sample.cs

The sample.cs file will be generated with the Lists and the content type information. To compare with the array of document names in the document library, a LINQ query can be used to filter the document.

List<string> docNames= new List<string>();

List<string> docExt= new List<string>();

docNames = {“Contract”, “Agreement”,”Case Study”, “Circular”};

docExt = {“.doc”, “.docx”,”.xls”, “.xlsx”};

Sample.SampleDataContext ctx = new Sample.SampleDataContext(SPContext.Current.Web.Url);

////The LINQ query to filter the documents with the specific name and extension

var result = from docs in ctx.MyDocuments.ScopeToFolder(“”,true) /// Get all the documents irrespective of folders

              where docnames.Contains(.docs.Name) && docExt.Contains(docs.Name)

              select docs;

The above code will filter the document based on name and extention from the MyDocuments document library in the Sample sharepoint site. With just single easy to understand query able to filter documents based on dynamic criteria