如何查询SPView对象

时间:2011-01-11 19:44:46

标签: c# sharepoint sharepoint-2007 wss-3.0

我有一个SPView对象,其中包含很多SPListItem个对象(视图中有很多字段)。

我只对其中一个领域感兴趣。我们称之为specialField

鉴于view和specialField,我想知道一个值是否包含在specialField中。

这是一种做我想做的事情:

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.

然而,迭代每个ListItem似乎不是最佳的,特别是因为可能有数百个项目。此查询将经常执行,因此我正在寻找一种有效的方法来执行此操作。

修改 我不会总是使用相同的视图,所以我的解决方案不能被硬编码(它必须足够通用,才能更改list,view和specialField。

将它转换为IEnumerable对象会更好吗?说这样的话:

list.GetItems(query).Cast<SPListItem>().Where(item => 
{
    return ((item[specialField] != null) && (item[specialField].ToString() == specialValue));
}).Count() > 0;

这会更有效率,还是我完全朝着错误的方向前进?

2 个答案:

答案 0 :(得分:3)

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();
string tmp = view.Query;
if(tmp.Contains("<Where>")) {
    //wrap the existing where clause in your needed clause (it should be an And i think)
    tmp = tmp.Insert(tmp.IndexOf("<Where>") + ("<Where>".Length), "<And><Eq><FieldRef Name='"+specialField+"'/><Value Type='Text'>"+specialValue+"</Value></Eq>");
    tmp = tmp.Insert(tmp.IndexOf("</Where>"), "</And>");
} else {
    //add a where clause if one doesnt exist
    tmp = "<Where><Eq><FieldRef Name='"+specialField+"'/><Value Type='Text'>"+specialValue+"</Value></Eq></Where>" + tmp;
}
query.Query = tmp;
SPListItemCollection items = list.GetItems(query);
if(item.Count > 0) {
    //My value is found. This is what I was looking for.
    //break out of the loop or return
} else {
    //My value is not found.
}

答案 1 :(得分:0)

您可以在 Caml 中执行查询。 This是理解Caml中查询的良好链接,this是指向自动构建查询的软件的链接。