tags:

views:

1063

answers:

3

I have an SPListItemCollection.

I basically want to get one of the items (randomly) in the collection and return it.

My method has a return type that expects an SPListItemCollection, so I dont mind having an SPListItemCollection that has just the one item in it and returning that.

Im not sure how to return an SPListItemCollection with this one item in it

how can i do this?

A: 

Select a random item in the collection. Seed a Rand object and then when you go to get a random number from it, use the bounds of the array to define the bounds of your random object (0, spListItemCollection.Count);

Take that item, wrap it in a new SPListItemCollection and return it.

Chris Holmes
its the wrapping the item into a new SPListItemCollection that is causing me the problem. I have got the item randomly etc... but dont know how to do the next part
raklos
You cannot create a new SPListItemCollection
Kusek
+2  A: 

I think you have to add the item to the collection you want to return, then you have to call update()

SPListItemCollection collListItemsDest; //collection to return
SPListItem oListDest = collListItemsDest.Add(); //add item to collection
oListDest["Field1_Name"] = "RANDOM"; //random item you retrieved
oListDest.Update();

Then you can return collListItemsDest
MSDN - SPListItemCollection add()

But really, you should think about returning just the item, not the collection. There is no point to return a collection if you always know its only going to have one item

OTisler
+2  A: 

On re-reading, it looks like you want to reduce the SPListItemCollection to a single item, but here's a way to get a SPListItemCollection with a single random item directly from the list:

private SPListItemCollection GetRandomItem(SPList list)
{
    Random random = new Random();
    int index = random.Next(0, list.ItemCount - 1);
    SPQuery query = new SPQuery();
    query.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Integer\">{0}</Value></Eq></Where>", index);
    return list.GetItems(query);
}
Rich Bennema
This should be the Best Answer. Just use the Random Number to get the Item ID and use the above method to get the Result you want
Kusek