我有一个 SPView
对象,其中包含许多 SPListItem
对象( View 中有很多字段)。
我只对其中一个领域感兴趣。我们称之为 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 似乎并不是最佳选择,尤其是因为可能有数百个项目。该查询将经常执行,因此我正在寻找一种有效的方法来执行此操作。
编辑 我不会总是使用相同的 View ,因此我的解决方案不能进行硬编码(它必须足够通用,以便可以更改列表、 View 和特殊字段。
将其转换为 IEnumerable 对象会更好吗?说这样的话:
list.GetItems(query).Cast<SPListItem>().Where(item =>
{
return ((item[specialField] != null) && (item[specialField].ToString() == specialValue));
}).Count() > 0;
这会更有效率还是我完全朝着错误的方向前进?
最佳答案
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.
}
关于c# - 如何查询SPView对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661865/