Join Class

Select random records in LINQ c# example

How to select random records in LINQ, like selecting random rows from database using LINQ.

Random rnd = new Random();

There are different ways to select random records or object from collection or random rows from database using LINQ.

Selecting random objects in LINQ
int _randomTake;
int _randomSkip;
_randomTake = GenerateRandomNumber();
_randomSkip = GenerateRandomNumber();
var _resultSet = objList.Skip(_randomSkip).Take(_randomTake);

Select random rows using LINQ

Selecting fixed number of records randomly from large record set in LINQ
Now let’s say you want to fetch fix number of rows from a large collection, and you need objects to be selected randomly.

 var _resultSet = objList.OrderBy(x => Guid.NewGuid()).Take(10);

You also can change the orderby clause to OrderByDescending in above LINQ query.

 var _resultSet = objList.OrderByDescending(x => Guid.NewGuid()).Take(10);

Another way of selecting one random object from collection, using random in LINQ

      Random rnd = new Random();
    List<blogobj> blogList = CFD.GetMyBlogList();
    var _randomizedList = from item in blogList
                         orderby rnd.Next()
                         select item;

Note: in above example we are selecting only one object from collection.

Select random records in LINQ C#: LINQ random rows example
LINQ (language integrated query) allow you to write query on database objects like, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join MVC Course