I have tried to edit my code to the following But dont seem to be the correct way:
public int Compare(object x, object y)
{
string s1 = (string)x;
string s2 = (string)y;
return DateTime.Compare(DateTime.ParseExact(s1.Substri开发者_C百科ng(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));
I have a data in a format of a08102011 in a array list.
Where 08 is the month, 10 is the day, 2011 is the year.
How can it be sorted in the way that?
a08102011
a09112011
Sorting an ArrayList with custom string:
Assuming your string format is using fixed width fields (always one character prefix, always two characters for days etc.) you could use a custom IComparer
implementation:
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());
Of course there is no real reason you should have to use an ArrayList
in the first place - use a strongly typed collection like List<string>
instead - the same concept applies there, just use an IComparer<string>
custom implementation.
Update: Strongly typed IComparer
It looks like you really are using a string array, not ArrayList
, so use the strongly typed version of the 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));
}
}
Then you can sort your array like this:
string[] items = new string[] { "a09112011", "a08102011" };
Array.Sort(items, new CustomComparer());
Finally: The Linq approach
Also, much shorter, you can use Linq instead - which does create a new sorted array though, so it's a little more compute intensive but that should not matter in the overall scheme of things:
string[] items = new string[] { "a09112011", "a08102011" };
items = items.OrderBy(x => DateTime.ParseExact(x.Substring(1),
"MMddyyyy",
CultureInfo.InvariantCulture))
.ToArray();
精彩评论