如何查询SPView对象
我有一个 SPView
对象,其中包含许多 SPListItem
对象(视图中有很多字段)。
我只对这些领域之一感兴趣。我们将其称为 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.
但是,迭代每个 ListItem 似乎并不是最佳选择,特别是因为可能有数百个项目。该查询将经常执行,因此我正在寻找一种有效的方法来执行此操作。
编辑 我不会总是使用相同的视图,因此我的解决方案不能进行硬编码(它必须足够通用,以便可以更改列表、视图和特殊字段。
将其转换为 IEnumerable 对象会更好吗?说这样的话:
list.GetItems(query).Cast<SPListItem>().Where(item =>
{
return ((item[specialField] != null) && (item[specialField].ToString() == specialValue));
}).Count() > 0;
这会更有效还是我完全朝着错误的方向前进?
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.
Would it better to cast it to an IEnumerable object? Say something like this :
list.GetItems(query).Cast<SPListItem>().Where(item =>
{
return ((item[specialField] != null) && (item[specialField].ToString() == specialValue));
}).Count() > 0;
Would this be more efficient or am I heading in the wrong direction entirely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 Caml 中执行查询。 这是一个用于理解 Caml 中的查询和 this 的好链接是自动构建查询的软件的链接。
You can execute queries in Caml. This is a good link for understanding queries in Caml and this is a link to software for building queries automatically.