C# – how to filter a list on SharePoint

asp.netcnetsharepoint-2007visual-studio-2008

I am using SharePiont Server 2007 Enterprise with Windows Server 2008 Enterprise, and I am using publishing portal template. I am developing using VSTS 2008 + C# + .Net 3.5. I have defined a custom list manully on a SharePoint site (all column types of the custom list are SharePoint built-in types), and I want to define some customized rules to filter this list to display only a part of the list. Any reference code?

EDIT1: Here is my current code. I have used such code to retrieved the items I need, but how to display the retieved items in a SharePoint list?

SPSite oSiteCollection = SPContext.Current.Site;
SPList oList = oSiteCollection.AllWebs[0].Lists["PeopleTest"];
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='Department'/>" +
               "<Value Type='Text'>Computer</Value></Eq></Where>";
SPListItemCollection collListItems = oList.GetItems(oQuery);

foreach (SPListItem oListItem in collListItems)
{
    writer.Write(oListItem["Department"].ToString()+"###");
} 

Best Answer

If you're using server (i.e., not client) dlls, you can use SPList.GetItems Method with SPQuery as a parameter:

SPSite oSiteCollection = SPContext.Current.Site;
SPList oList = oSiteCollection.AllWebs["Site_Name"].Lists["List_Name"];
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='Schedule'/>" +
        "<Value Type='CHOICE'>2 weeks</Value></Eq></Where>";
SPListItemCollection collListItems = oList.GetItems(oQuery);

foreach (SPListItem oListItem in collListItems)
{
    Label1.Text += SPEncode.HtmlEncode(oListItem["Title"].ToString()) 
        + " -- " + SPEncode.HtmlEncode(oListItem["EndDate"].ToString())   
        + "<BR>";
}

Note that foreach part of this example code which displays data in HTML format, is provided only for example. You may use the same rendering as you use at present. The key is to use SPQuery and .GetItems(...).

If you use client dlls, see this link and others from MSDN (this link is only an example, it is relevant for SharePoint Team Services Client API).