Tag: linq

  • C#: LINQ Join and order by

    Recently, I had a requirement which read as this:

    Allocate payments into the details by contribution type such that oldest due amounts are first allocated based on the allocation order specified.

    To re-phrase it in programming terms, we had a collection that contained due amounts with contribution type and date due. We also had a rule set that defined which contribution type has to be allocated first. Overriding this rule set was the oldest due amount rule.

    So the collection with the due amount and date is defined as below:

    public class Detail
    {
    	public string contribType { get; set; }
    	public decimal amount { get; set; }
    	public DateTime reportingDate { get; set; }
    
    	public Detail(string contribType, decimal amount, DateTime reportingDate)
    	{
    		this.contribType = contribType;
    		this.amount = amount;
    		this.reportingDate = reportingDate;
    	}
    }

    The rule for allocation is defined as:

    public class CodeValue
    {
    	public string codeValue { get; set; }
    	public string allocateOrder { get; set; }
    
    	public CodeValue(string codeValue, string allocateOrder)
    	{
    		this.codeValue = codeValue;
    		this.allocateOrder = allocateOrder;
    	}
    }

    We have multiples ways to implement the logic. Here is an example using LINQ.

     var sortedResult= from detail in detailCollection
                                   join codeValue in codeValueCollection on detail.contribType equals codeValue.codeValue
                                   into joinedDetails
                                   from fullDetail in joinedDetails.DefaultIfEmpty()
                                   orderby detail.reportingDate, fullDetail.allocateOrder
                                   select detail;

    By looping through the resulting ‘sortedResult’ collection, one can easily satisfy the requirement. Elegant code with LINQ.