I have a database table that represents Events. The table has 2 main fields EventDate and EventTitle.
I am trying to group the events by year to be displayed to the user. I am trying to use a Linq query to pull the distinct years that have events and for each year there should be a list of events in that year. So each record in the list would have a year and list of Events
I assume this can be done with one linq query but my linq knowledge is basic. So far I have only gotten the distinct years in a list with this query:
var yearsList = (from e in Events
select e.EventDate.Year).Distinct();
How do I add a list of events to each year record?
var yearsList = from e in Events
group e by e.EventDate.Year into g
select new { Year = g.Key, Events = g };
That will get you a list of objects with a "Year" property and an "Events" property (all the events for that year).
Have a look at this handy reference: 101 Linq Samples.
You're really looking for an ordered group.
var yearsList = from e in Events
group e by e.EventDate.Year into g
orderby g.Key
select g;
foreach(var yearGroup in yearsList)
{
int year = yearGroup.Key;
foreach(Event e in yearGroup)
{
// do something with the events
}
}
Assuming you have the following Event class
public class Event
{
public int Year { get; set; }
public string Name { get; set; }
public static Event[] GetEvents()
{
return new Event[]
{
new Event{ Name="Event1", Year=2001},
new Event{ Name="Event2", Year=2002},
new Event{ Name="Event3", Year=2003},
new Event{ Name="Event4", Year=2001},
new Event{ Name="Event5", Year=2002},
new Event{ Name="Event6", Year=2003},
new Event{ Name="Event7", Year=2001},
new Event{ Name="Event8", Year=2002},
new Event{ Name="Event9", Year=2003}
};
}
}
public class Program
{
static void Main(string[] args)
{
var groupedEvents = Event.GetEvents().GroupBy(e => e.Year);
foreach (var groupedEvent in groupedEvents)
{
Console.WriteLine("Year:{0}",groupedEvent.Key);
foreach (var evnt in groupedEvent)
{
Console.WriteLine("---- Event Name:{0}",evnt.Name);
}
}
}
}
The above should give you events grouped by year
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With