按特定格式对数据进行排序
本文关键字:排序 数据 定格 格式 | 更新日期: 2023-09-27 18:05:28
我试着编辑我的代码如下但似乎不是正确的方法:
public int Compare(object x, object y)
{
string s1 = (string)x;
string s2 = (string)y;
return DateTime.Compare(DateTime.ParseExact(s1.Substring(1), "MMddyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact(s2.Substring(1), "MMddyyyy", CultureInfo.InvariantCulture));
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
if (scheduleListBox.Items.Count == 0)
{
try
{
//Get all the directories name that start with "a"
fileNames = myStore.GetDirectoryNames("a*");
//Sort according to the schedule month
//Array.Sort(fileNames);
Array.Sort(new Compare(fileNames));
我在数组列表中有一个格式为a08102011的数据。
08年, 是月,10为日;2011是年。
怎么能这样排序呢?
a08102011
a09112011
用自定义字符串排序数组列表:
假设您的字符串格式使用固定宽度字段(总是一个字符前缀,总是两个字符的天等),您可以使用自定义IComparer
实现:
public class CustomComparer : IComparer
{
public int Compare(object x, object y)
{
string s1 = (string) x;
string s2 = (string) y;
return DateTime.Compare(DateTime.ParseExact(s1.Substring(1), "MMddyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact(s2.Substring(1), "MMddyyyy", CultureInfo.InvariantCulture));
}
}
..
ArrayList items = new ArrayList();
items.Add("a08102011");
items.Add("a09112011");
items.Sort(new CustomComparer());
当然,没有真正的理由你必须在第一个地方使用ArrayList
-使用强类型集合像List<string>
代替-同样的概念适用于那里,只是使用IComparer<string>
自定义实现。
Update:强类型IComparer
看起来你真的在使用字符串数组,而不是ArrayList
,所以使用CustomComparer
的强类型版本:
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
string s1 = (string) x;
string s2 = (string) y;
return DateTime.Compare(DateTime.ParseExact(s1.Substring(1), "MMddyyyy", CultureInfo.InvariantCulture),
DateTime.ParseExact(s2.Substring(1), "MMddyyyy", CultureInfo.InvariantCulture));
}
}
那么你可以这样排序你的数组:
string[] items = new string[] { "a09112011", "a08102011" };
Array.Sort(items, new CustomComparer());
最后:Linq方法
也更短,你可以用Linq来代替——它会创建一个新的排序数组,所以它的计算量更大一些,但这在整体方案中应该无关紧要:
string[] items = new string[] { "a09112011", "a08102011" };
items = items.OrderBy(x => DateTime.ParseExact(x.Substring(1),
"MMddyyyy",
CultureInfo.InvariantCulture))
.ToArray();