What's Here?
- Members: 300,354
- Replies: 825,775
- Topics: 137,423
- Snippets: 4,418
- Tutorials: 1,147
- Total Online: 1,738
- Members: 118
- Guests: 1,620
|
This is a snippet that first randomizes a Generic List, then retrieve N number of items
|
Submitted By: PsychoCoder
|
|
|
Rating:
|
|
Views: 528 |
Language: C#
|
|
Last Modified: July 5, 2009 |
Instructions: Add the following to your class
using System.Collections;
using System.Collections.Generic;
using System.Linq
Requires .Net 3.5 or higher |
Snippet
/// <summary>
/// method for returning N number of random items from a generic list
/// </summary>
/// <typeparam name="T">Item type</typeparam>
/// <param name="list">Generic list we wish to retrieve from</param>
/// <param name="count">number of items to return</param>
/// <returns></returns>
public IEnumerable<T> RandomizeGenericList<T>(List<T> list, int count)
{
List<T> randomList = new List<T> ();
Random random = new Random ();
while (list.Count > 0)
{
//get the next random number between 0 and
//the list count
int idx = random.Next(0, list.Count);
//get that index
randomList.Add(list[idx]);
//remove that item so it cant
//be added again
list.RemoveAt(idx);
}
//return the specified number of items
return randomList.Take(count);
}
Sample usage:
public IEnumerable<SomeItem> GetRandomItems(int count)
{
List<SomeItem> list = new List<SomeItem> ();
//...add your items here
return RandomizeGenericList(list, count);
}
Copy & Paste
|
|
|
|