【问题标题】:Get Month name and year from list从列表中获取月份名称和年份
【发布时间】:2016-07-28 16:15:38
【问题描述】:

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

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 =

【问题讨论】:

    标签: c# entity-framework linq c#-4.0


    【解决方案1】:

    几个月并使用 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. 上找到

    【讨论】:

      【解决方案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()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-03
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        相关资源
        最近更新 更多