1

I am trying to retrieve the month name and the year using LINQ from a list that has 2 properties without repeating the name of the months and the year.

public class Record
{
    public int Id { get; set; }
    public DateTime Date { get; set; }
}

DateTime d1 = new DateTime(2015, 1, 14);
DateTime d2 = new DateTime(2016, 3, 12);
DateTime d3 = new DateTime(2016, 4, 17);
DateTime d4 = new DateTime(2015, 5, 19);
DateTime d5 = new DateTime(2016, 6, 10);

List<Record> dates = new List<Record>
{
    new Record { Id= 1, Date = d1 },
    new Record { Id= 2, Date = d2 },
    new Record { Id= 3, Date = d3 },
    new Record { Id= 4, Date = d4 },
    new Record { Id= 5, Date = d5 }
};

//Month should be in string format (January,June, etc)
// Get Year and Months from that list withour repeating the names 
//List<string> months =
//List < string > years =
DavidG
  • 113,891
  • 12
  • 217
  • 223
Gilberto Quintero
  • 397
  • 1
  • 6
  • 18

2 Answers2

4

For months and using Linq:

 List<string> months = dates.Select(d => d.Date.ToString("MMMM"))
                            .Distinct()
                            .ToArray();

Information on the ToStirng format for the month name can be found on MSDN here.

and for years:

List<string> years = dates.Select(d => d.Date.Year.ToString())
                          .Distinct()
                          .ToArray();

Although it is unclear how you want the list of years to look.

Information on Distinct can be found on MSDN here.

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
2

With an extension method to simplify it (taken from here):

static class DateTimeExtensions
{
    public static string ToMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
    }
}

You can do this:

var months = dates.Select(r => r.Date.ToMonthName())
    .Distinct();

var years = dates.Select(r => r.Date.Year)
    .Distinct();

Note that I've given years as int here, if you want strings, then just add ToString().

Community
  • 1
  • 1
DavidG
  • 113,891
  • 12
  • 217
  • 223