Reputation: 211
I have a SortedList that has DateTime for the key and int for the value. The DateTime value will have the hour and minute attached. Is it possible to write a C# linq procedure to group the SortedList by a single Date ignoring the hour and sum-up the value?
Upvotes: 3
Views: 2301
Reputation: 117029
By a single date?
Easy!
Assuming you have declared the variable singleDate
as a DateTime
to get the sum of, here is the query:
var result = (
from key in sortedList.Keys.Cast<DateTime>()
where key.Date == singleDate.Date
select (int)sortedList[key]
).Sum();
I've used singleDate.Date
to drop any time information that singleDate
may have, but otherwise this should be fairly straight forward.
SortedList
is a little painful to work with LINQ. Can you tell me why you are using it?
Upvotes: 0
Reputation: 13019
With LINQ it is pretty straightforward:
from item in list
group item by item.Key.Date into g
select new
{
Sum = g.Sum(a => a.Value),
Values = g
};
Upvotes: 7