Tip of the day: Random sort a List of objects with Linq

Let’s say you have a list of objects and you want a random presentation to your website visitor. Below is a simple, but effective random algorithm in C# with Linq-to-object by using the GUID type (see line 10 below).

   1:  List<MemorySearchResult> list = Session["MemoryList"] as List<MemorySearchResult>;
   2:              
   3:  // see if list is already in user session
   4:  if (list == null)
   5:  {
   6:      // list not in session, so create a new one
   7:      var newList = myRepository.GetListOfObjects();
   8:   
   9:      // randommize
  10:      list = newList.OrderBy(tempGuid => Guid.NewGuid()).ToList();
  11:   
  12:      // store in session
  13:      Session["MemoryList"] = list;
  14:  }
  15:   
  16:  // now list is randomized and stored in session and ready to use

 

Easy does it!