Steven
Steven

Reputation: 211

C# Linq group by DateTime ignore hours and minutes

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

Answers (2)

Enigmativity
Enigmativity

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

as-cii
as-cii

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

Related Questions