我想從「行情」列表中獲得一個隨機列表項。我目前有一個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