开发者

Grouping data with a LINQ query

I have a C# DataTable with 5 columns in it. I only care about two of the columns in the DataTable. The two columns I c开发者_开发问答are about are called "CreateDate" and "ID". They are a DateTime and string. The DateTime represents the date on which a ticket was submitted. The ID uniquely represents a ticket.

I am trying to write a LINQ statement that shows me the number of tickets created per date. However, I cannot figure out how do this. Can someone show me how to do this?

Thank you!


I believe something like this will work:

var result = from ticket in TicketTable
group ticket by ticket.CreateDate.Date into g
select new {Date = g.Key, Count = g.Count() };


class Program
{
    static void Main(string[] args)
    {
        List<Ticket> tickets = new List<Ticket>();

        tickets.Add(new Ticket() { CreateDate = DateTime.Now, Id = 1 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(1), Id = 2 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(1), Id = 3 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(2), Id = 4 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(2), Id = 5 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(3), Id = 6 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(3), Id = 7 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(4), Id = 8 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(5), Id = 9 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(6), Id = 10 });
        tickets.Add(new Ticket() { CreateDate = DateTime.Now.AddDays(7), Id = 11 });

        var query = tickets.
                    GroupBy(t => t.CreateDate.Date).
                    Select(g => new { Date = g.Key, Count = g.Count() });

        foreach (var g in query)
        {
            Console.WriteLine("{0} - {1}", g.Date, g.Count);
        }

        /* Outputs:
            7/24/2010 12:00:00 AM - 1
            7/25/2010 12:00:00 AM - 2
            7/26/2010 12:00:00 AM - 2
            7/27/2010 12:00:00 AM - 2
            7/28/2010 12:00:00 AM - 1
            7/29/2010 12:00:00 AM - 1
            7/30/2010 12:00:00 AM - 1
            7/31/2010 12:00:00 AM - 1 */
    }

    class Ticket
    {
        public int Id { get; set; }
        public DateTime CreateDate { get; set; }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜