Search code examples
c#.netgeneric-collections

Check for decreasing values in a list


I have a list populated from a DataGrid:

List<string> balances = new List<string>();

foreach (DataRow dr in dt.Rows)
{
    if((dr[1].ToString() != null) && (dr[1].ToString() != string.Empty))
    {
        balances.Add(dr[1].ToString());
    }
}

The DataGrid has been previously sorted into chronological order of ascending date, these are expected payments, so the balances in the list should decrease.

I need to write a bit of code to check if the current list item is lower than the previous list item, but this is currently eluding me, can someone help?


Solution

  • var lastBalance = decimal.MaxValue;
    foreach (DataRow dr in dt.Rows)
    {
        if (!string.IsNullOrEmpty(dr[1].ToString()))
        {
            var currentBalance = Convert.ToDecimal(dr[1]);
            if (currentBalance < lastBalance)
            {
                lastBalance = currentBalance;
                balances.Add(dr[1].ToString());
            }
            else
            {
                //TODO: Invalid list
                //throw ... OR
                break;
            }
        }
    }