skip to Main Content

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.

2

Answers


  1. You can use LINQ to sort the rows based on the Currency property. Assuming your DataTable has a column named Price with a custom data type Currency.

    var sortedRows = dataTable.AsEnumerable()
        .OrderBy(row => ((Currency)row["Price"]).Value)
        .CopyToDataTable();
    

    See this .NET Fiddle.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search