How to query the SPView object

Posted by Hugo Migneron on Stack Overflow See other posts from Stack Overflow or by Hugo Migneron
Published on 2011-01-11T19:44:46Z Indexed on 2011/01/11 19:54 UTC
Read the original article Hit count: 228

Filed under:
|
|
|

I have a SPView object that contains a lot of SPListItem objects (there are many fields in the view).

I am only interested in one of these fields. Let's call it specialField

Given that view and specialField, I want to know if a value is contained in specialField.

Here is a way of doing what I want to do :

String specialField = "Special Field";
String specialValue = "value";
SPList list = SPContext.Current.Site.RootWeb.Lists["My List"];
SPView view = list.Views["My View"]; //This is the view I want to query

SPQuery query = new SPQuery();
query.Query = view.Query;
SPListItemCollection items = list.GetItems(query);
foreach(SPListItem item in items)
{
    var value = item[specialField];
    if(value != null) && (value.ToString() == specialValue)
    {
        //My value is found. This is what I was looking for.
        //break out of the loop or return
    }
}

//My value is not found.

However, iterating through each ListItem hardly seems optimal, especially as there might be hundreds of items. This query will be executed often, so I am looking for an efficient way to do this.

EDIT I will not always be working with the same view, so my solution cannot be hardcoded (it has to be generic enough that the list, view and specialField can be changed.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sharepoint