I have an ArrayList of strings that look as below, I would like to output a new ArrayList sorted in a particular way. But not sure of a good way of sorting it. Help will be really appreciated!
Original (can be in any random order):
1:1
0:0
0:1
2:1
1:0
2:0
Output:
2:0
2:1
1:0
1:1
0:0
0:1
While I think both of the other answers are spot-on, I’m going to assume you’re unfamiliar with some of the features of .NET 2.0 and .NET 3.5 they used. Let’s take it one step at a time.
So you’re given an
ArrayListholding the following data:First of all, nothing is wrong with using RegEx; perhaps a minor performance penalty. If the strings are really as simple as this, you can just use
Split:However, since you said you’re using .NET 4, you really shouldn’t be using
ArrayListat all — note that it requires you to cast your values to their appropriate type, e.g.string mystring = myArray[i] as string.There are plenty of great features you’re not taking advantage of, such as generics (in the .NET Framework since 2.0). Let’s write a function that is given an
ArrayList, but returns a sorted genericList<string>(a list that only holds strings). Let’s have a look:Now, the above code works, but is really long. Note that you have to create a class just to hold these two values, make that class implement IComparable, etc, etc. Pretty annoying!
.NET 3.5 came out with some great features, including anonymous types and LINQ. Let’s change our code to use both of those features.
Our entire function is just one line now, and most of the code is comments. I encourage you to learn about and start using some of these features; it’ll make your code a lot easier to read and write 😉
Hope this helped!
Edit: In resopnse to your comment:
It looks like you’re sorting by the second number, ascending, and then by the first number, descending.
Simply change the code above to use: