views:

54

answers:

4

Hi,

I am facing a problem with LINQ.

Here is the code,

    public class TimeObject
    {
        public DateTime Time { get; set; }
    }

    private void TestLINQ()
    {
        List<TimeObject> results = new List<TimeObject>();

        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 0, 10, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 0, 20, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 0, 30, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 0, 40, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 0, 50, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 1, 10, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 1, 20, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 1, 30, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 1, 40, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 2, 15, 0)});
        results.Add(new TimeObject() { Time = new DateTime(2010, 8, 1, 2, 30, 0)});

        var counts = from result in results
                        group result by result.Time.Date.Hour into groupedResult
                        select new { Hour = groupedResult.Key, Count = groupedResult.Count() };

        foreach (var count in counts)
        {
            MessageBox.Show(count.Hour + " - " + count.Count);
        }
    }

The output I expect is 0 - 5, 1 - 4, 2 - 2

But I am always getting 0 - 12. Why it is not grouping by hour?

Please help me. Thanks.

+2  A: 

.Date trims off the hour etc. portion, giving you just a date. Try grouping by result.Time.Hour instead.

Will A
A: 

Try converting group result by result.Time.Date.Hour into the hour value directly using a DateTime conversion rather than using a property of the Time object. The LINQ statement may be stopping the grouping operation at the Time property.

Tahbaza
+1  A: 

When you use .Date on a DateTime the time will be set to zero. So use this:

var counts = from result in results
             group result by result.Time.Hour into groupedResult
             select new { Hour = groupedResult.Key, Count = groupedResult.Count() };
lasseespeholt
+1  A: 

change result.Time.Date.Hour to result.Time.Hour

liho1eye
Gr8. Thanks a lot. By changing it to result.Time.Hour it works :)
Jai