2016-07-28 89 views
1

我试图从具有2个属性的列表中检索使用LINQ的月份名称和年份,而不重复月份和年份的名称。从列表中获取月份名称和年份

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 = 

回答

2

随着扩展方法来简化它(从here拍摄):

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

你可以这样做:

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

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

请注意,我已经给年int这里,如果你想要字符串,那么只需添加ToString()

4

数月,使用LINQ:

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

ToStirng格式月名称的信息可以在MSDN here.

,多年来发现:

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

虽然目前还不清楚你想如何查看年份列表。

关于Distinct的信息可以在MSDN here.上找到

相关问题