Ciupaz
Ciupaz

Reputation: 699

Datatable: Select values based on datetime

Having a DataTable with these values (for example):

 Quantity       ReferenceDate
87.000000   2011-11-24 15:12:26.990
58.000000   2011-11-24 15:12:26.030
87.000000   2011-11-24 12:18:27.180
58.000000   2011-11-24 13:12:27.027
87.000000   2011-11-24 19:22:27.563
13.000000   2011-11-24 19:40:27.123

having a DateTime variable that has only the hour, for example

DateTime mySelectDate = new DateTime (2011,12,15,19,00,00)

how can I obtain the sum(Quantity) for the values that "fall" in that hour?

In my example I should get Sum(Quantity) = 100 (87 + 13)

Luigi

Upvotes: 0

Views: 1101

Answers (1)

vc 74
vc 74

Reputation: 38179

Using Linq to DataSet:

DateTime mySelectDate = new DateTime (2011,12,15,19,00,00);
DateTime endDate = mySelectDate.AddHours(1);

var sum = table.Rows.AsEnumerable().
               .Where(row =>       
               {
                 var referenceDate = row.Field<DateTime>("ReferenceDate");
                 return ((referenceDate >= mySelectDate ) && (referenceDate < endDate));
               })
               .Sum(row => row.Field<double>("Quantity"));

Upvotes: 3

Related Questions