In this article, I will show how to perform random sort list c# asp.net.The .Net 3.5 framework has Linq,it is a very good feature, it allows us to perform complex operations with efficiency .
Step 1: Create an asp.net mvc project and right click on the controller folder and create a new controller and name it as HomeController. Inside the HomeController copy and paste the following code.
public class RandomSortController : Controller
{
//
// GET:/RandomSort/
models db = new models();
public ActionResult Index()
{
return View(db.Departments.OrderBy(emp => Guid.NewGuid()).ToList());
}
}
Step 2: Right click on the Share folder and create a razor view named as index. Copy and paste the following code.
@modelIEnumerable<MVC_tutorials.Models.Department>
<h2>Random Sort a List Using LINQ</h2>
<p>
@Html.ActionLink("CreateNew", "AddDepartment")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.DepartmentID)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DepartmentID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "EditDepartmentDetails", new { id = item.DepartmentID }) |
@Html.ActionLink("Delete", "DeleteDepartment", new { id = item.DepartmentID })
</td>
</tr>
}
</table>
Description: Run the application, the department object list get randomly sorted and displayed on the page.