Link to home
Start Free TrialLog in
Avatar of countrymeister
countrymeister

asked on

LINQ help

I have a datatable with two columns - a date field (datetime) and currency field(string)

I need to get the max date from the datatable where the date is less than some derived date
and the Currency matches a currency field

strCurrency = "USD"
dBusDate = '06/01/2010'

In this example I need to get the max date less than dBusDate and currency = USD from the datatable
Avatar of kaufmed
kaufmed
Flag of United States of America image

How about this?
static void Main(string[] args)
{
    DataTable t = new DataTable();
    DataRow r;

    t.Columns.Add("currency", typeof(string));
    t.Columns.Add("BusDate", typeof(DateTime));

    for (int i = 0; i < 10; i++)
    {
        r = t.NewRow();
        r["currency"] = "USD";
        r["BusDate"] = new DateTime(2010, 06, 01 + i);
        t.Rows.Add(r);
    }

    var result = from row in t.Rows.Cast<DataRow>()
                 group row by row["currency"].ToString() into g
                 select new { Maximum = g
                     .Where(x => Convert.ToDateTime(x["BusDate"]) < new DateTime(2010, 6, 4) && x["currency"].ToString() == "USD")
                     .Max(y => Convert.ToDateTime(y["BusDate"])) };

    foreach (var row in result)
    {
        Console.WriteLine("Max Date: {0}", row.Maximum);
    }

    Console.ReadKey();

}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of countrymeister
countrymeister

ASKER

thanks
Not a problem, glad I was able to help.  ;=)