European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting - HostForLIFE.eu :: Using The IComparable And IComparer Interface In C#

clock May 19, 2020 07:54 by author Peter

One of the most used functionalities in our C# classes is the ability to sort the different instances of a class. This is mostly done when we create a generic List of our class type and next, we want to sort our class based on some condition. Today, we will see how this is done in our C# classes

Creating the Class

We will create a .NET core console application using Visual Studio 2019 Community edition as below,

Next, we create a Student Class inside the “Program.cs” file as below,
  public class Student : IComparable<Student> 
  { 
   
      public int ID { get; set; } 
      public string Name { get; set; } 
      public string Program { get; set; } 
      public int Year { get; set; } 
      public float GPA { get; set; } 
   
      public int CompareTo(Student otherItem) 
      { 
          var status = (this.GPA > otherItem.GPA) ? 1 : ((this.GPA == otherItem.GPA) ? 0 : -1);  
          return status; 
      } 
  } 


Let us look at the code in detail. To make the class sortable we need to implement the IComparable<T> interface. In this interface we need to code the “CompareTo” function. In this function another instance of the same class is passed in and then we compare the two to order them. We base this on the GPA field and hence when we sort a List<Student> list, we will get the class items sorted by GPA in ascending order. Note that if the return value is zero, this means that the classes are equal in sort order, if the return value is 1 (positive number), then the current class is higher in the sort and if the value is -1 (negative number) then the input class is higher in the sort order.

To test this out, we write the following code in the Main function as below,
  class Program 
      { 
          static void Main(string[] args) 
          { 
   
              var students = new List<Student>(); 
   
              var studentA = new Student() { ID = 1, Name = "John Doe", Program = "BCS", Year = 2020, GPA = 2.75F }; 
              var studentB = new Student() { ID = 1, Name = "Jane Doe", Program = "BCS", Year = 2020, GPA = 3.4F }; 
              var studentC = new Student() { ID = 1, Name = "Mary Jane", Program = "BCS", Year = 2020, GPA = 2.71F }; 
   
              students.Add(studentA); 
              students.Add(studentB); 
              students.Add(studentC); 
   
              Console.WriteLine($"Items not in any order"); 
              foreach(var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.WriteLine(); 
   
              students.Sort(); 
   
              Console.WriteLine($"Items in ascending order"); 
              foreach (var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.WriteLine(); 
   
              students.Sort(new DescendingComparer()); 
   
              Console.WriteLine($"Items in descending order"); 
              foreach (var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.ReadKey(); 
          } 
      } 
   
      public class DescendingComparer : IComparer<Student> 
      { 
          public int Compare(Student a, Student b) 
          { 
              var status = (a.GPA > b.GPA) ? -1 : ((a.GPA == b.GPA) ? 0 : 1); 
              return status; 
          } 
      } 


In the first case, we print the list of student classes as entered in the list. Then, we sort the list which will list the students in ascending order based on the GPA field. Finally, if we want to reverse the order and sort the student classes in descending order by GPA field we create a new DescendingComparer class which implements the IComparer<Student> interface and sort the records in the reverse order of what we did before.



European ASP.NET Core Hosting - HostForLIFE.eu :: Action Result in ASP.NET Core API

clock May 5, 2020 10:12 by author Peter

This article overview action result which are used in ASP.NET Core and Core API. We will understand both, which are available in two different assemblies of ASP.NET Core Microsoft.AspNetCore.Mvc and System.Web.Http.

ObjectResult
ObjectResult primary role is content negotiation. It has some variation of a method called SelectFormatter on its ObjectResultExecutor. You can return an object with it, and it formats the response based on what the user requested in the Accept header. If the header didn’t exist, it returns the default format configured for the app. It’s important to note that if the request is issued through a browser, the Accept header will be ignored, unless we set the RespectBrowserAcceptHeader to true when we configure the MVC options in Startup.cs. Also, it doesn’t set the status code, which causes the status code to be null. ObjectResult is the super type of following:

AcceptedResult

AcceptedAtActionResult
AcceptedAtRouteResult
BadRequestObjectResult
CreatedResult
CreatedAtActionResult
CreatedAtRouteResult
NotFoundObjectResult
OkObjectResult

AcceptedResult

An AcceptedResultthat returns an Accepted (202) response with a Location header. It indicates that the request is successfully accepted for processing, but it might or might not acted upon. In this case, we should redirect the user to a location that provides some kind of monitor on the current state of the process. For this purpose, we pass a URI.
public AcceptedResult AcceptedActionResult() 
    { 
        return Accepted(new Uri("/Home/Index", UriKind.Relative), new { FirstName = "Peter",LastName="Scott" }); 
    } 


AcceptedAtActionResult
An AcceptedAtActionResult action result returns an accepted 202 response with a location header.
public AcceptedAtActionResult AcceptedAtActionActionResult() 

return AcceptedAtAction("IndexWithId", "Home", new { Id = 2, area = "" }, new { FirstName = "Peter",LastName="Scott" }); 


AcceptedAtRouteResult
An AcceptedAtRouteResult returns an Accepted (202) response with a Location header. It's the same as AcceptedResult, with the only difference being that it takes a route name and route value instead of URI.
public AcceptedAtRouteResult AcceptedAtRouteActionResult() 

return AcceptedAtRoute("default", new { Id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 


BadRequestResult
An ObjectResult, when executed. will produce a Bad Request (400) response. It indicates a bad request by user. It does not take any argument.
public BadRequestResult BadRequestActionResult() 

  return BadRequest(); 


BadRequestObjectResult
This is similar to BadRequestResult, with the difference that it can pass an object or a ModelStateDictionary containing the details regarding the error.
public BadRequestObjectResult BadRequestObjectActionResult() 

        var modelState = new ModelStateDictionary(); 
        modelState.AddModelError("Name", "Name is required."); 
        return BadRequest(modelState); 


CreatedResult

CreatedResult returns a Created (201) response with a Location header. This indicates the request has been fulfilled and has resulted in one or more new resources being created.
public CreatedResult CreatedActionResult() 
    { 
        return Created(new Uri("/Home/Index", UriKind.Relative), new { FirstName = "Peter", LastName = "Scott" }); 
    } 


CreatedAtActionResult
CreatedAtActionResult that returns a Created (201) response with a Location header.
public CreatedAtActionResult CreatedAtActionActionResult() 
    { 
        return CreatedAtAction("IndexWithId", "Home", new { id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 
    } 


CreatedAtRouteResult
CreatedAtRouteResult that returns a Created (201) response with a Location header.
public CreatedAtRouteResult CreatedAtRouteActionResult() 
    { 
        return CreatedAtRoute("default", new { Id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 
    } 


NotFoundResult
This represents a StatusCodeResult that when executed, will produce a Not Found (404) response.
public NotFoundResult NotFoundActionResult() 
    { 
        return NotFound(); 
    } 

NotFoundObjectResult
This is similar to NotFoundResult, with the difference being that you can pass an object with the 404 response.
public NotFoundObjectResult NotFoundObjectActionResult() 
    { 
        return NotFound(new { Id = 1, error = "There was no customer with an id of 1." }); 
    } 


OkResult
This is a StatusCodeResult. When executed, it will produce an empty Status200OK response.
public OkResult OkEmptyWithoutObject() 

return Ok(); 


OkObjectResult

An ObjectResult, when executed, performs content negotiation, formats the entity body, and will produce a Status200OK response if negotiation and formatting succeed.
public OkObjectResult OkObjectResult() 
    { 
        return new OkObjectResult(new { Message="Hello World !"}); 
    } 


NoContentResult

The action result returns 204 status code. It’s different from EmptyResult in that EmptyResult returns an empty 200 status code, but NoContentResult returns 204. Use EmptyResult in normal controllers and NoContentResult in API controllers.
public NoContentResult NoContentActionResult() 
    { 
        return NoContent(); 
    } 


StatusCodeResult

StatusCodeResult accepts a status code number and sets that status code for the current request. One thing to point is that you can return an ObjectResult with and status code and object. There is a method on ControllerBase called StatusCode (404, new {Name = "Peter Scott”}), which can take a status code and an object and return an ObjectResult.
public StatusCodeResult StatusCodeActionResult() 
    { 
        return StatusCode(404); 
    } 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in