Skip to main content

DotNet: Generic Sorting Class

Recently, I was searching for a generic sorting approach on dotnet List. Many articles (Like one, two..etc) were suggesting standard way of creating IComparer implementer class and using that with generic list (List <T>) in our application. Writing IComparer class for every business object not only take huge time also create challenges in code management when it grow considerably. So, here is simple and effective generic sorting class which can be used with any custom business object and can be sorted on any one of its properties.

All you have to do is, copy paste the complete code in to a new .cs file.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Srushti.Business
{
public class GenericComparer<T> : IComparer<T>
{
string _propName = string.Empty;
bool _sortDirection = true;
public GenericComparer(string propertyName, bool SortAscending)
{
_propName = propertyName;
_sortDirection = SortAscending;
}

private int CompareAsc(object o1, object o2)
{
if (o1 is IComparable)
return ((IComparable)o1).CompareTo(o2);
else if (o1.Equals(o2))
return 0;
else
return o1.ToString().CompareTo(o2);
}
#region IComparer<T> Members

public int Compare(T x, T y)
{
PropertyInfo pi = x.GetType().GetProperty(_propName);
object o1 = pi.GetValue(x, null);

pi = y.GetType().GetProperty(_propName);
object o2 = pi.GetValue(y, null);

if (_sortDirection == false)
return CompareAsc(o1, o2) * -1;
else
return CompareAsc(o1, o2);
}
#endregion
}
}


...and start consuming it as shown below. You have to supply, property name (as String) on which you want to sort the list and sorting direction (Boolean, true for ascending and false for descending) to GenericComparer() constructor.

private void Form1_Load(object sender, EventArgs e)
{
List empList = new List();
empList.Add(new Employee() { ID = 1, Name = "Three" });
empList.Add(new Employee() { ID = 2, Name = "Two" });
empList.Add(new Employee() { ID = 3, Name = "One" });

/*** Generic Comparer ***/
empList.Sort(new GenericComparer("Name", true));

foreach (Employee em in empList)
MessageBox.Show(em.ID.ToString());
}

public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}

Please Note: Class properties with complex data types like DateTime, Nullable might require special attention.

Comments

Popular posts from this blog

Windows forgets visual effects settings on log-out or reboot for non-administrator account

Steps given here worked for me with Windows 7 SP1. Hope you may find it useful.

Start -> Run-> cmd (press enter) -> type SystemPropertiesPerformance.exeThis gets you the "System Properties" window, go to  Advanced tab -> Performance Settings -> Visual Effects tab and choose "Adjust for best performance" and click OK. Note: While doing all these UAC doesn't show-up as all changes you are doing will be saved in your logged-in profile account.

Reference material used: http://msdn.microsoft.com/en-us/library/ee330866.aspx

Feel free to comment your findings.

Hangfire with In-Memory Storage (ASP.Net MVC 4/5)

This is in continuation to my previous post: Hangfire with ASP.Net MVC : Simplest Code To Start with.

In this post we will see how Hangfire can be configured without the SQL Server as its backend for job scheduling, instead, manage all in-memory

1) Create ASP.Net MVC 4/5 Projects
2) in web.config file
3) Run Install-Package HangFire -Version 1.6.17 or visit here for latest version: https://www.nuget.org/packages/Hangfire/1.6.17
3) Run Install-Package Hangfire.MemoryStorage -Version 1.5.2 or visit here for latest version https://www.nuget.org/packages/Hangfire.MemoryStorage/
4) I am simply updating a table with a primary key (auto incremented), and string field "StampTime" with current date and time.
5) Open Global.asax.cs and paste below shown code.
6) Run the app and check the database.


using Hangfire; using Hangfire.Common; using Hangfire.MemoryStorage; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using…

Hangfire with ASP.Net MVC : Simplest Code To Start with

It seems many are looking for using Hangfire with ASP.Net MVC 4 / 5+ SQL Server here is the simplest code example for you to start quick.

I am using Visual Studio 2017 Community Edition

1) Create ASP.Net MVC 4/5 Projects
2) <add key="owin:AutomaticAppStartup" value="false" /> in web.config file
3)Run Install-Package HangFire -Version 1.6.17 or visit here for latest version: https://www.nuget.org/packages/Hangfire/1.6.17
4) From the sample code, make sure you create database in SQL Server DB and update the connection string.
5) I am simply updating a table with a primary key (auto incremented), and string field "StampTime" with current date and time.
6) Open Global.asax.cs and put this code.
7) Run the app and check the database.

The example code also showcase a hack on how to run jobs with few seconds interval.

namespace HangFireDemo { publicstaticclassMyTasks { publicstaticasync Task<int> MinuteTick() { awa…