如何查询SPView对象
我有一个包含很多SPListItem
对象的SPView
对象(视图中有很多字段)。
我只对其中一个领域感兴趣。 我们称之为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几乎不是最佳的,特别是因为可能有数百个项目。 此查询将经常执行,因此我正在寻找一种有效的方法来执行此操作。
编辑我不会总是使用相同的视图,所以我的解决方案不能硬编码(它必须足够通用,以便可以更改列表,视图和specialField。
将它转换为IEnumerable对象会更好吗? 说这样的话:
list.GetItems(query).Cast().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("")) { //wrap the existing where clause in your needed clause (it should be an And i think) tmp = tmp.Insert(tmp.IndexOf(" ") + (" ".Length), ""+specialValue+" "); tmp = tmp.Insert(tmp.IndexOf(" "), ""); } else { //add a where clause if one doesnt exist tmp = ""+specialValue+" " + 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. }
您可以在Caml中执行查询。 这是理解Caml中查询的一个很好的链接, 这是一个自动构建查询的软件链接。