Search code examples
c#.netlinqsortingoop

Sorting is not working on Custom DataType (Currency Class) in C#


Hi Folks i have one field Price and it has Custom datatype i.e. Class that represents a currency which has properties i.e. CurrencySymbol, CurrencyCode and CurrencyValue. And i want to apply sorting on Price by its value. Can someone please help me on that.

public class Currency 
    {
        public decimal Value { get; set; }
        public string Symbol { get; set; }
        public string Code { get; set; }
    }
var rows = dataTable.Select(filters, "Price Asc");

I have read many articles but not getting exact solution.


Solution

  • there is 2 approach for that First (quick) : sort your enumerable using linq and lambda

    lets assume you have an Enumerable (Like List and Array) of Currency type named currencies

    you can sort it using Linq and lambda as blow example :

    //for ascending order and store the rows in a List
    var orderedCurrencies = currencies.OrderBy(p=>p.Value).ToList();
    
    //for descending order and store the rows in a List
    var orderedCurrencies = currencies.OrderByDescending(p=>p.Value).ToList();
    

    for more investigation you should refer to This documentation

    The Second Approach is more OOP friendly and i suggest to use this when you want to respect object oriented software architecture

    Fist Implement IComparable interface for your Currency Object So that the Object Can be Compared like the Example blow :

    public class Currency : IComparable<Currency>
    {
        [...]
    
        public int CompareTo(Currency that)
        {
            return this.Value.CompareTo(that.Balance);
        }
    }
    

    and sort it with Linq as the example blow :

    //for ascending order and store the rows in a List
    var orderedCurrencies = currencies.Order().ToList();
    
    //for descending order and store the rows in a List
    var orderedCurrencies = currencies.OrderDescending().ToList();
    

    for more investigation you should read This documentation