first of all, im still kinda new to coding and have not that much knowledge ^^ So here is my problem, I need to create a class/method that can sort a list, that look like this:
.Add("1");
.Add("1.1");
.Add("1.2");
.Add("1.1.1-1");
.Add("1.1.1-1usa");
.Add("7.2");
.Add("8.");
.Add("9.");
the list should be ascend(?) meaning, it starts with the lowest number going up to the highest.
I tried to make char arrays out of them and then compare each char with an if-statement. some mor informations: 1.1.1 > 1.1 and as you can see, there are also letters inside. If someone has an idea I would be very thankful for every tip :)
CodePudding user response:
The cleanest approach here is to implement comparer between two items. See:How to use a custom Comparer to sort an Array in a different lexical order?
The basic idea is that you need to implement the comparison between two items:
public static int CompareStrings(string s1, string s2)
{
// TODO: your code here
// since your string represents version numbers to avoid
//comparing them lexicographically first parse them to numbers.
}
And now you can sort using this comparator:
string[] myStrings = { ... };
Array.Sort(myStrings, CompareStrings);
Another similar option is to implement your own comparator class that implements IComparer<string> and pass it to .OrderBy(x => x.Name, new MySorter());
CodePudding user response:
I have used basic alphabetic sorting and this is the result:
1
1.1
1.1.1-1
1.1.1-1usa
1.2
7.2
8.
9.
As you can see:
1 < 1.1 < 1.1.1-1* < 1.2 < 7.2 < 8. < 9.
// 1.1.1-1* means:
// anything, starting with 1.1.1-1
I believe we can agree on that. As far as the letters are concerned:
1.1.1-1 < 1.1.1-1usa
Also this seems logical, because nothing comes before something.
So it looks like basic alphabetic sorting does the trick, or do you disagree?
