在列表中对月份进行排序

本文关键字:排序 列表 | 更新日期: 2023-09-27 18:18:01

我有一个字符串列表,其中包含一年中的月份。我需要能够排序这个列表,所以月份是按月排序的,而不是按字母顺序。我一直在寻找一段时间,但我看不出我找到的任何解决方案。

下面是一个如何添加月份的示例。它们是根据SharePoint列表中的字段动态添加的,因此它们可以按任何顺序排列,并且可以有重复项(我正在使用Distinct()删除它们)。

List<string> monthList = new List<string>();
monthList.Add("June");
monthList.Add("February");
monthList.Add("August");

想把这个重新排序到:

February
June
August

在列表中对月份进行排序

您可以将字符串解析为DateTime,然后使用月份整数属性进行排序。查看这里支持的月份名称:http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx

像这样:

var sortedMonths = monthList
    .Select(x => new { Name = x, Sort = DateTime.ParseExact(x, "MMMM", CultureInfo.InvariantCulture) })
    .OrderBy(x => x.Sort.Month)
    .Select(x => x.Name)
    .ToArray();

您可以将月份名称解析为日期(它假设是当前的年份和第1天):

monthList = monthList.OrderBy(s=> DateTime.ParseExact(s, "MMMM", new CultureInfo("en-US"))).ToList();

您可以使用Dictionary<int,string>代替,使用int作为月份编号进行排序,然后按键排序。

IDictionary<int,string> monthList = new Dictionary<int,string>();
monthList.Add(6, "June");
monthList.Add(2, "February");
monthList.Add(8, "August");
var sorted = monthList.OrderBy(item => item.Key);

如果坚持使用仅包含表示月份的字符串的列表,则必须使用另一个数据源来检索该月份的索引,以便对列表进行排序。例如,可以用月份名作为string键,用int索引作为值来填充字典。然后,您可以使用重载方法List<T>.Sort(Comparison<T>)并传入一个比较函数,该函数按名称返回月份的索引(通过将它们传递到字典中)。

但是,我建议首先不要使用原始字符串,而是使用表示月份的更结构化的数据类型。然后,您可以将索引嵌入到数据结构本身中,并根据该值进行排序,从而为您提供更自包含的解决方案。

你需要一个SortedList<>…如

SortedList<int,string> monthList=new SortedList<int,string>();
monthList.Add(6,"June");
monthList.Add(2,"February");
monthList.Add(8,"August");   
IList<string> sortedMonthList=monthList.Values;

然后使用sortedMonthList。

这可以通过使用seldon的答案来创建一个函数来改进,就像

public static int MonthNumFromName(String monthname)
{ ... }

,然后使用

monthList.Add(MonthNumFromName("June"),"June");

好吧,我猜没有任何排序技术,只有纯月作为字符串。

您可以使用Dictionary<int, string>和int来对月份进行排序。

如果我没有弄错的话,你实际上有一个月的列表作为字符串,那么你为什么不这样做呢?

List<string> months = new List<string> { "January", "February", ..., "December" };
var yourSortedMonthsInYourOriginalList = months.Where(m => 
                                              originalList.Any(o => o == m)).ToList();

您可以构建自己的排序类:

    static void Main(string[] args)
    {
        List<string> monthList = new List<string>();
        monthList.Add("June");
        monthList.Add("February");
        monthList.Add("August");
        monthList.Sort(new _mysort());
    }
    private class _mysort : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            if (x=="February" && y=="June")
            {
                return -1;
            }
            return 0;
        }
    }

但我认为你应该使用Enum,并将其转换为字符串,然后你可以使用数字来排序。

 enum months
    {
        Jan =0,
        Feb =1
    }

:

       List<months> mlist = new List<months>() { months.Feb, months.Jan };
        //sort
        mlist = mlist.OrderBy(e => (int)e).ToList();
       //print
        mlist.ForEach(e => Console.WriteLine(e.ToString()));

创建enum并为每个月分配int值。用linq排序