我想从“行情”列表中获得一个随机列表项。我目前有一个web部件,它具有用于选择要显示的报价类型的自定义属性。 “行情”列表中引用了以下类别“企业,技术和财务”)。目前,我正在使用一个foreach循环来显示特定类别的所有引号。我有CAML查询来过滤要显示的引号类型。在web部件的自定义属性中输入的值用于CAML查询以显示引号。生成一个随机数得到一个随机列表项
下一步是显示一个特定类别的随机引用,但我不太确定如何实现这一点。下面是我的代码currenlty已经随机位尚未完成不肯定就如何做到这一点。
protected void Page_Load(object sender, EventArgs e)
{
if (this.WebPart != null && this.WebPart.PracticeArea != null)
{
string PracticeArea = this.WebPart.PracticeArea; //get the value of the property
//getting a reference to the site location
string webUrl = SPContext.Current.Site.AllWebs["practices"].Url;
//Getting the Quotes list
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{
try
{
//getting the Quotes list
SPList quotesList = web.Lists["Quotes"];
//SPListItemCollection collLisItems = quotesList.Items; not needed
//CAML query to filter or obtain the correct quote based on Area. Value for Area is
//passed from the custom property and used in the caml query
SPQuery quotesbySector = new SPQuery();
//creating an object to handle our random list item selection
//not too sure whether this is correct
Random rndQuote = new Random();
int num = rndQuote.Next();
//string camlquery1 = "<Where><Eq>" + "<FieldRef Name='Area'/>" + "</Eq></Where>";
string camlquery1 = @"
<Where>
<Eq>
<FieldRef Name='Area'/>
<Value Type='Text'>" + PracticeArea + @" </Value>
</Eq>
</Where>";
quotesbySector.Query = camlquery1;
SPListItemCollection collListItems = quotesList.GetItems(quotesbySector);
//SPListItem firstQuote = collListItems[0];
//for each loop might need to be removed, as we are only interested in getting a
//random quote and not all quotes
foreach (SPListItem item in collListItems)
{
string quotes = (string)item["Quote"];
string quotesSource = (string)item["Source"];
string quotesYear = (string)item["Year"];
//string quotesArea = (string)item["Area"]; //not needed used for test purposes
plhQuotes.Controls.Add(new LiteralControl(quotes + "<br/>" + "<br/>" + quotesSource +
"<br/>" + "<br/>" + quotesYear + "<br/>" + "<br/>"));
}
}
catch (Exception err)
{
plhErrors.Controls.Add(new LiteralControl(err.ToString()));
}
}
}
}
}
我肯定有一个简单的方法来实现这一目标。任何的建议是大大的应用调整它。
在此先感谢。
您尝试完成代码时面临什么特定问题? – phoog 2012-02-06 18:00:57
您当前的代码正在处理错误地生成随机数。你的当前代码会产生一个新的随机种子,这种方式往往会导致非随机序列。什么不适合你的工作,你似乎没有在本网站上获得帮助所需的关键部分,完全理解你的问题是什么,只是问一个关于这个问题的问题。你也想创建一个不大于你的收藏大小的数字。 rndQuote.Next()的位置是正确的,你初始化它的位置应该在循环的外部。 – 2012-02-06 18:05:42
@丹尼尔 - 我打算低估这个问题,直到你试图完全实现你正在尝试做的事情,并且你完全解释什么是和什么不工作。这将允许您解决一些设计问题(即以不正确的方式初始化随机类)并试图获得问题的全部范围。 – 2012-02-06 18:07:01