Query Sharepoint List

29/09/2012 20:37

//Query SharePoint list by CAML query, Linq, lambda expression

 

using System;
using System.Linq;
using Microsoft.SharePoint;
 
 SPList list = web.Lists["Lookup List"];
                   
                    //Select items by CAML Query
                    SPQuery query = new SPQuery();
                    query.Query=string.Format("Peto");
 
                    var listItems=list.GetItems(query);
                    foreach (SPListItem item in listItems)
                    {
                        Console.WriteLine("Item: {0}, {1}:", item["Title"].ToString(), item["Meno"].ToString());
                    }
 
                    //Select items by Linq
                    var linqItems = from SPListItem polozka in list.Items
                                    where (polozka["Meno"].ToString().Contains("Peto"))
                                    select polozka;
 
                    foreach (SPListItem item in linqItems)
                    {
                        Console.WriteLine("Item: {0}, {1}:", item["Title"].ToString(), item["Meno"].ToString());
                    }
                 
                    //Select items by lambda expression
                    var lambdaItems = list.Items.Cast()                        .Where(itm => Convert.ToString(itm["Meno"]).Contains("Peto"));
 
                    foreach (SPListItem item in lambdaItems)
                    {
                        Console.WriteLine("Item: {0}, {1}:", item["Title"].ToString(), item["Meno"].ToString());
                    }
                  
//Caml Query, how to write other way

SPQuery query = new SPQuery();

query.Query = string.Concat(

"<Where><Eq>",

"<FieldRef Name='ChamVideoKey'/>",

"<Value Type='Text'>" + this.ItemKey + "</Value>",

"</Eq></Where>");

query.RowLimit = 1;

 

SPListItemCollection items = list.GetItems(query);

if (items.Count == 1)

item = items[0];