Select two (or more) unique random items from list

By Alon Havivi

Use the this code to create a list of unique random numbers, based on your SharePoint List:

If you want to choose a subset of 2 or more unique sharepoint list items in a range of your list items


List

<SPListItem> randomItems = new List<SPListItem>(); ;
base.CreateChildControls();
base.CreateChildControls(); SPList list = SPContext.Current.Web.Lists["Tasks"];
SPListItemCollection items = list.Items;
foreach (SPListItem item in items)
{

randomItems.Add(item);

}

Random
random = new Random();
int index = random.Next(0, randomItems.Count - 1);
SPListItem randomItem1 = randomItems[index];
this.Controls.Add(new LiteralControl("Random item 1:" + randomItem1["Title"].ToString()));
this.Controls.Add(new LiteralControl("<BR>"));
randomItems.RemoveAt(index);

index = random.Next(0, randomItems.Count - 1);

SPListItem randomItem2 = randomItems[index];
this.Controls.Add(new LiteralControl("Random item 2:" + randomItem2["Title"].ToString()));
.
.
.

Here you can find the source code you need to build a web part: http://eggheadcafe.com/FileUpload/-1253398195_TwoUniqueItems.zip

Related FAQs

Get random item from SharePoint list
Select two (or more) unique random items from list  (389 Views)
Create New Account