2011-01-11 78 views
2

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

我只对这些领域感兴趣。我们称之为specialField

鉴于该视图和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. 

然而,通过各列表项的迭代似乎不是最佳,尤其是因为可能有几百个项目。这个查询会经常执行,所以我正在寻找一种有效的方法来做到这一点。

编辑 我不会总是以相同的观点来工作,所以我的解决方案不能被硬编码(它是通用足够的列表,查看和specialField是可以改变的。

会是更好它转换为一个IEnumerable对象说是这样的:??

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

这将是更有效的还是我在错误的方向完全走向

+0

为什么不在查询中附加子句。一个例子http://msdn.microsoft.com/en-us/library/ms457534.aspx – 2011-01-11 21:01:28

+0

因为我不知道这个查询会是什么样子(即查看查询)。例如,如果有一个OrderBy子句,我不能只在后添加一个where子句(它会给出一个 ... ... ...并且不起作用 – 2011-01-11 21:28:08

+1

Where子句看起来像 ...虽然它看起来像多个根节点,但只有发送给SPQuery的整个事件被SPView对象封装在标记中,只需查看在Google上使用SharePoint CAML – Colin 2011-01-11 22:53:44

回答

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. 
} 
0

你可以执行查询CamlThis是理解Caml查询的好链接,this是一个链接到用于自动构建查询的软件。