I have a dataset for an articles web site. Each article has datetime, but I can't separate them according to datetime with Linq.
For Example, this web site.
As you can see dataset generates month month and year year.
Using linq how can I separate this dataset?
I thought maybe I can if I use like this List<List<Article>>
but this defeat.
Say I have a class:
public class Article
{
public DateTime PostDate {get;set;}
}
or a Datarow with a PostDate
column
And a list of these Articles:
List<Article>
I'd like to group these articles into first Year
and then Month
, based on the PostDate
using Linq.
So that I can output them as follows:
I understand, you're trying to group the articles by year and then by month.
Let's say you have the following Article class:
class Article
{
public DateTime PostDate { get; set; }
public string Title { get; set; }
public Article(DateTime postDate, string title)
{
PostDate = postDate;
Title = title;
}
}
And the following sample data:
var list = new List<Article>
{
new Article(new DateTime(2012, 12, 1), "A"),
new Article(new DateTime(2012, 12, 1), "B"),
new Article(new DateTime(2012, 11, 2), "C"),
new Article(new DateTime(2012, 11, 2), "D"),
new Article(new DateTime(2013, 12, 1), "E")
};
You could do the grouping like this:
var grouped = list.GroupBy(a => a.PostDate.Year)
.Select(a => new { Year = a.Key, Items = a.GroupBy(i => i.PostDate.Month)
.Select(i => new { Month = i.Key, Titles = i.Select(t => t.Title)})
.OrderBy(i => i.Month)})
.OrderBy(a => a.Year);
And output it like this:
foreach (var year in grouped)
{
Console.WriteLine("Year: " + year.Year);
foreach (var month in year.Items)
{
Console.WriteLine(" Month: " + month.Month);
foreach (var title in month.Titles)
{
Console.WriteLine(" Title: " + title);
}
}
}
Here's the output:
Year: 2012
Month: 11
Title: C
Title: D
Month: 12
Title: A
Title: B
Year: 2013
Month: 12
Title: E
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments