How to list all month names, e.g. for a combo?

后端 未结 16 1025
栀梦
栀梦 2020-12-23 14:38

At the moment I\'m creating a DateTime for each month and formatting it to only include the month.
Is there another or any better way to do this?

16条回答
  •  醉酒成梦
    2020-12-23 14:57

    A way to retrieve a dynamic culture specific list of month names in C# with LINQ.

    ComboBoxName.ItemsSource= 
    System.Globalization.CultureInfo.
    CurrentCulture.DateTimeFormat.MonthNames.
    TakeWhile(m => m != String.Empty).ToList();
    

    OR

    In this example an anonymous object is created with a Month and MonthName property

    var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
     .TakeWhile(m => m != String.Empty)
     .Select((m,i) => new  
     {  
         Month = i+1,  
         MonthName = m
     }) 
     .ToList();
    

    PS: We use the method TakeWhile because the MonthNames array contains a empty 13th month.

提交回复
热议问题