[英]Sorting months in a list
我有一個字符串列表,其中包含一年中的幾個月。 我需要能夠對此列表進行排序,以便月份按月排序,而不是按字母順序排列。 我一直在尋找一段時間,但我無法看到我已經找到的任何解決方案。
這是一個如何添加月份的示例。 它們是基於SharePoint列表中的字段動態添加的,因此它們可以按任何順序排列,並且可以有重復項(我將使用Distinct()刪除它們)。
List<string> monthList = new List<string>();
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,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);
您可以將月份名稱解析為日期(它假定當前年份和第1天):
monthList = monthList.OrderBy(s=> DateTime.ParseExact(s, "MMMM", new CultureInfo("en-US"))).ToList();
如果您堅持只有表示月份的字符串列表,那么您必須使用另一個數據源來檢索該月份的索引,您可以通過該索引對列表進行排序。 例如,您可以使用月份名稱作為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");
以上。
創建enum
並為每個月分配int
值。 用linq對事物進行排序。
好吧,我想沒有任何排序技術,只有純月作為字符串。
您可以使用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 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()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.