在列表中对月份进行排序

我有一个字符串列表,其中包含一年中的几个月。 我需要能够对此列表进行排序,以便月份按月排序,而不是按字母顺序排列。 我一直在寻找一段时间,但我无法看到我已经找到的任何解决方案。

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

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

想将此重新排序为:

 February June August 

您可以将字符串解析为DateTime ,然后使用month整数属性进行排序。 请参阅此处获取支持的月份名称: 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(); 

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

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

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

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

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

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

你需要一个SortedList <> ..比如

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

然后使用sortedMonthList进行其余的工作。

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

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

然后使用

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

以上。

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

您可以使用Dictionary并使用int来对月份进行排序。

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

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

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

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

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

  enum months { Jan =0, Feb =1 } 

喜欢:

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

创建enum并为每个月分配int值。 用linq对事物进行排序。