DarrylGodden
DarrylGodden

Reputation: 1534

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?

Upvotes: 0

Views: 422

Answers (4)

Jodrell
Jodrell

Reputation: 35716

erm, uses lazy evaluation, only goes as far as the first increase.

  var last = decimal.MaxValue;
  var decreasing = true;
  foreach(var value in dataTable.AsEnumerable()
                            .Select(r => r.Field<string>(1))
                            .Where(s => !string.IsNullOrWhiteSpace(s))
                            .Select(Decimal.Parse))
  {
      if (last < value)
      {
          decreasing = false;
          break;
      }

      last = value;
  }

Upvotes: 0

ThunderGr
ThunderGr

Reputation: 2367

if (Convert.ToDecimal(balances[balances.Count - 1]) >= Convert.ToDecimal(balances[balances.Count -2]) MessageBox.Show("The new value is not lower than the previous","Error");.

You need to make sure this is not the first item in the list and that the String can convert to Decimal, in order for this to work.

EDIT: Of course, you could check if the new item is lower than the previous, before you put it in the balances list.

Upvotes: 0

Raphael
Raphael

Reputation: 1687

try with this, it puts your table in a list, and with the zip method you can compare the values, selecting those that have the current value that is lower that the previous

List<DataRow> list = dt.AsEnumerable().ToList();
var result = list.Zip(list.Skip(1), 
(p, c) => new {current = c.fieldName, previous = p.fieldName})
.Where(f => f.current < f.previous)
.Select(a => a.current)
.ToList();

Upvotes: 0

Alexander Schmidt
Alexander Schmidt

Reputation: 5723

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;
        }
    }
}

Upvotes: 3

Related Questions