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

后端 未结 16 984
栀梦
栀梦 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 15:09

    This method will allow you to apply a list of key value pairs of months to their int counterparts. We generate it with a single line using Enumerable Ranges and LINQ. Hooray, LINQ code-golfing!

    var months = Enumerable.Range(1, 12).Select(i => new { I = i, M = DateTimeFormatInfo.CurrentInfo.GetMonthName(i) });
    

    To apply it to an ASP dropdown list:

    // 
    ddlMonths.DataSource = months;
    ddlMonths.DataTextField = "M";
    ddlMonths.DataValueField = "I";
    ddlMonths.DataBind();
    

提交回复
热议问题