saif
saif

Reputation: 123

Count number of occurrences of each month in db table asp.net linq

I have a table which contains a date col.

I want to use LINQ query and count the occurrence of each month and display it like month, occurrence of month in the table

1=2(1 is month, 2 is number of occurrence),2=5,3=12 and so on using asp.net.

Can somebody please tell me how to do it.

Thanks in advance.

Upvotes: 0

Views: 1068

Answers (2)

qamar
qamar

Reputation: 1447

You can do the following if you want to use lambda instead of long linq. Although you need to convert numeric month to something texual.

var somedates = new List<DateTime>() { 
            DateTime.Now, 
            DateTime.Now.AddDays(10), 
            DateTime.Now.AddMonths(1), 
            DateTime.Now.AddMonths(1).AddDays(5)};

var months = somedates.GroupBy(x => x.Month).Select(g => new {Name = g.Key, Count = g.Count()});

Upvotes: 0

mshsayem
mshsayem

Reputation: 18008

How about this?

var dates = Enumerable.Range(1, 5).Select(i=>new DateTime(2015,i%3+1,1));
var grouped = dates.GroupBy(d => d.Month).Select(g => string.Format("{0}={1}", g.Key, g.Count()));
// Now grouped will have your desired data (list of occurrences)

I have used dummy dates here. You need to Select the date column from the database instead.

Upvotes: 1

Related Questions