C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 300,354 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,738 people online right now. Registration is fast and FREE... Join Now!





Retrieve N number of random items from a Generic List

This is a snippet that first randomizes a Generic List, then retrieve N number of items

Submitted By: PsychoCoder
Actions:
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


  1. /// <summary>
  2. /// method for returning N number of random items from a generic list
  3. /// </summary>
  4. /// <typeparam name="T">Item type</typeparam>
  5. /// <param name="list">Generic list we wish to retrieve from</param>
  6. /// <param name="count">number of items to return</param>
  7. /// <returns></returns>
  8. public IEnumerable<T> RandomizeGenericList<T>(List<T> list, int count)
  9. {
  10.     List<T> randomList = new List<T>();
  11.     Random random = new Random();
  12.  
  13.     while (list.Count > 0)
  14.     {
  15.         //get the next random number between 0 and
  16.         //the list count
  17.         int idx = random.Next(0, list.Count);
  18.  
  19.         //get that index
  20.         randomList.Add(list[idx]);
  21.  
  22.         //remove that item so it cant
  23.         //be added again
  24.         list.RemoveAt(idx);
  25.     }
  26.  
  27.     //return the specified number of items
  28.     return randomList.Take(count);
  29. }
  30.  
  31. Sample usage:
  32. public IEnumerable<SomeItem> GetRandomItems(int count)
  33. {
  34.     List<SomeItem> list = new List<SomeItem>();
  35.  
  36.     //...add your items here
  37.  
  38.     return RandomizeGenericList(list, count);
  39. }

Copy & Paste


Comments


Martyr2 2009-07-05 16:44:55

Be advised that the method "Take" was introduced in .NET 3.5 and you are also required to have the System.Linq namespace in there to get access to the method for the List generic type.

PsychoCoder 2009-07-05 17:55:27

Thanks Martyr2, I forgot all about that. I'll add that now


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month