Posted by: R Manimaran | June 23, 2011

Selecting Random ListItems from SharePoint List using Lambda Expression

Selecting Random ListItems

I have a list with the following list items. I need to select the records in the list on a Random fashion. I have tried in Lambda and get it done. It will be useful to someone.

SPList myList = oSPWeb.Lists.Cast()
                            .FirstOrDefault(l => l.Title == "Test");

 if (myList != null)
  {
  SPQuery query = new SPQuery();
  Random rnd = new Random();
  IOrderedEnumerable<SPListItem> Items = myList.GetItems(query)
                                             .Cast(<SPListItem>)
                                             .AsEnumerable()
                                             .OrderBy((i => rnd.Next()));

         foreach (SPListItem item in Items)
         {
           Console.WriteLine(item[SPBuiltInFieldId.Title].ToString());
         }
}

The Output will be as below


Leave a comment

Categories