Home > Mobile >  Selecting multiple random objects from an html database (Entity Framework)
Selecting multiple random objects from an html database (Entity Framework)

Time:12-04

I need to select 3 random events from the database by a certain parameter (their type). How can I do this?

Right now, I use foreach to select everything, but I need to select 3 objects and select them randomly.

@foreach (Event entity in Model)
{
    @if (entity.Type=="Концерт")
    {
        <img  src="~/images/@entity.TitleImagePath"/>
    }
}

CodePudding user response:

Use the Random class to generate random indexes and select random items from the list of objects:

public ActionResult Test()
{
    // Prepare a random list
    var list = new List<Event>();
    var cnt = db.Events.Count();
    var entities = db.Events.Where(e => e.Type=="something")).ToList();
    var rnd = new Random();
    for (int i=0; i < 3 && cnt > 0; i  ) list.Add(entities[rnd.Next(cnt)]);
    // Render the view
    return View(list);       
}

And then enumerate the prepared list in the view:

@model List<Event>
@foreach (Event entity in Model)
{ 
    <img  src="~/images/@entity.TitleImagePath"/>                
}

CodePudding user response:

Try this way

var result = await this.context.Events.Where(x => x.Type == "Концерт").OrderBy(x => Guid.NewGuid()).Take(3).ToListAsync();
  • Related