LINQ小组的问题

时间:2010-08-20 23:23:52

标签: c# .net .net-3.5 c#-3.0

我遇到了LINQ的问题。

这是代码,

    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);
        }
    }

我期望的输出是 0 - 5, 1 - 4, 2 - 2

但我总是得到0-12。为什么不按小时分组呢?

请帮帮我。感谢。

4 个答案:

答案 0 :(得分:2)

。日期修剪小时等部分,只给你一个约会。尝试按result.Time.Hour进行分组。

答案 1 :(得分:1)

.Date上使用DateTime时,时间将设置为零。所以使用这个:

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

答案 2 :(得分:1)

result.Time.Date.Hour更改为result.Time.Hour

答案 3 :(得分:0)

尝试使用DateTime转换直接将group result by result.Time.Date.Hour转换为小时值,而不是使用Time对象的属性。 LINQ语句可能正在停止Time属性的分组操作。