Ali
Ali

Reputation: 98

Random selection of query result Linq

i have a query which will result 10 or 20 or any number number of rows. Below is the query.

   var q = (from c in session.DB.Question where c.Level='1' && c.Group='1' select c);

This query can give me any number of rows.

But i have to show just 1 row from the result. I can select top 1/first but i would like select randomly.

i saw a topic about this: How to request a random row in SQL? but i want it in LinQ

Please help me how to get random row from the result.

Upvotes: 1

Views: 3619

Answers (4)

Ali
Ali

Reputation: 98

Thanks all. i found it and working:

        var q = (from c in Session.DB.WinQuestionSet
                 where c.Level == "easy" && c.Grade == "1"
                 select c).OrderBy(x => Guid.NewGuid()).Take(1).Single();
        label1.Text = q.Text;

Upvotes: 1

Chris
Chris

Reputation: 639

I assume that your questions has an Id. Please see example below. I used Random class to generate random number.

        List<Question> questions = new List<Question>
        {
            new Question { Id = 10, Name = "What?" },
            new Question { Id = 12, Name = "How?" },
            new Question { Id = 32, Name = "When?" },
            new Question { Id = 41, Name = "Where?" },
        };
        var q = (from c in questions select c);

        int i = 1;
        Dictionary<int, int> questionKeys = new Dictionary<int, int>();

        foreach (var item in questions)
        {
            questionKeys.Add(i, item.Id);
            i++;
        }

        Random rdm = new Random();
        int randomRow = rdm.Next(1, q.Count());

        var questionId = questionKeys.Where(x => x.Key == randomRow).Select(x => x.Value).Single();

        var result = q.Where(x => x.Id == questionId).Single();

        Console.WriteLine(result.Name);

Upvotes: 0

Alex R.
Alex R.

Reputation: 195

Assuming data is your data rows:

Random rand = new Random();
var row = data.ElementAt(rand.Next(data.Count));

Note that this does not work for Linq to SQL, and thus should be used after you query your db.

Upvotes: -1

Backs
Backs

Reputation: 24923

Sort items by random value and select first:

var q = (from c in session.DB.Question 
         where c.Level =='1' && c.Group =='1' 
         select c)
        .OrderBy(o => SqlFunctions.Rand())
        .First();

Upvotes: 3

Related Questions