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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: