我试图将我的代码编辑为以下但似乎不是正确的方法:
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));
Run Code Online (Sandbox Code Playgroud)
我在数组列表中有a08102011格式的数据.
其中08是月, 10是日, 2011是年.
怎么能按照那种方式排序?
a08102011
a09112011
使用自定义字符串对ArrayList进行排序:
假设您的字符串格式使用固定宽度字段(总是一个字符前缀,总是两个字符,等等),您可以使用自定义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());
Run Code Online (Sandbox Code Playgroud)
当然,没有任何理由你首先必须使用一个ArrayList- 使用类似强类型的集合List<string>- 相同的概念适用于那里,只需使用IComparer<string>自定义实现.
更新:强类型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));
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样对数组进行排序:
string[] items = new string[] { "a09112011", "a08102011" };
Array.Sort(items, new CustomComparer());
Run Code Online (Sandbox Code Playgroud)
最后:Linq方法
而且,更短,你可以使用Linq - 虽然它确实创建了一个新的排序数组,所以它的计算密集程度更高,但这在整体方案中无关紧要:
string[] items = new string[] { "a09112011", "a08102011" };
items = items.OrderBy(x => DateTime.ParseExact(x.Substring(1),
"MMddyyyy",
CultureInfo.InvariantCulture))
.ToArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |