Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have a C# variable which references a SharePoint list.

I need to iterate over each list item and do a conditional check.

I would like to use a linq call to filter out some of the data before I get into the loop.

Here is how I reference the list:

SPList list = root.Lists[LISTNAME];

And I want to do something like:

var items = from li in list.items
    where li.field.Contains("value")
    select li;

Is this possible? I am not sure if the standard namespace System.Linq can be used with SharePoint.

Thanks, Andrew

share|improve this question

2 Answers 2

up vote 5 down vote accepted

If you need to use Linq, you could go with SPMetal. But you can expect better performance by using CAML queries, like this:

SPWeb   web   = SPContext.Current.Web;
SPList  list  = web.Lists[LISTNAME];
SPQuery query = new SPQuery
{
    Query = @"<Where>
                 <Contains>
                    <FieldRef Name='Field' />
                    <Value Type='Text'>your value</Value>
                 </Contains>
              </Where>"
};
SPListItemCollection items = list.GetItems(query);
share|improve this answer
    
Thanks. Is there a way I can do something like: <Value Type='Text'>" + dynamicValue + "</Value> – andrewb Jun 4 '13 at 22:55
    
Sure, just append a String.Format and sanitize your input. – Rubens Farias Jun 4 '13 at 22:58
    
What if I have a list item ID and would like to get a field text based on the ID? – SearchForKnowledge Feb 23 at 15:08
1  
@SearchForKnowledge, you could use SPList.GetItemById, or in CAML <Where><Eq><FieldRef Name='ID'/><Value type='Counter'>123</Value></Eq></Where> – Rubens Farias Feb 23 at 15:37
    
@RubensFarias Thank you! – SearchForKnowledge Feb 23 at 16:59

You probably want the Microsoft.Sharepoint.Linq namespace, instead of System.Linq. You can find it here. Microsoft also has some documentation on Linq to SharePoint here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.