gpt4 book ai didi

c# - 如何查询 SPView 对象

转载 作者:行者123 更新时间:2023-11-30 22:41:55 24 4
gpt4 key购买 nike

我有一个 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 和 specialField 可以更改。

将其转换为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com