hoda mohammed hoda mohammed - 29 days ago 12
ASP.NET (C#) Question

How to use the same query which has the random value after I click next button

Now the problem is I have that query

var question = _repository.tbl_TestQuestion
.Where(x => x.nCourseId == courseId && x.nChapterId == chapterId && x.bActive == true)
.OrderBy(x => Guid.NewGuid()).Take(10).ToList();


when I click the next button to the next question it random the query again I don't need to random again I just need it to select from the 10 questions that already I random it

so any help

Answer

You can check a Session in the 'Page_Load` of the page. If it does not exist create a new Guid, otherwise get the Guid from the Session.

public string myGuid;

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["guid"] == null)
    {
        myGuid = Guid.NewGuid().ToString();
        Session["guid"] = myGuid;
    }
    else
    {
        myGuid = Session["guid"].ToString();
    }
}

Now you can use the Guid anywhere on the page.

var question = _repository.tbl_TestQuestion
    .Where(x => x.nCourseId == courseId && x.nChapterId == chapterId && x.bActive == true)
    .OrderBy(x => myGuid).Take(10).ToList();

UPDATE

It seems ordering by a Guid stored as a variable does not work .OrderBy(x => myGuid). Not even when parsing the myGuid variable .OrderBy(x => Guid.Parse(myGuid)).

You can either store the entire tbl_TestQuestion as a Session after the initial sorting an re-use that or sort the questions randomly when loading them from the Database (if you use one)

public _repository.tbl_TestQuestion questionList;

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["question"] == null)
    {
        questionList = _repository.tbl_TestQuestion
            .Where(x => x.nCourseId == courseId && x.nChapterId == chapterId && x.bActive == true)
            .OrderBy(x => Guid.NewGuid()).Take(10).ToList();

        Session["question"] = questionList;
    }
    else
    {
        questionList = Session["question"] as _repository.tbl_TestQuestion;
    }
}