In the example you've given, you could just sort them as strings. But I'd strongly advise you not to do that - otherwise "11.0.0" would be seen as earlier than "2.0.0".
Instead, I'd suggest creating a Version
class with major/minor/patch values. That can implement IComparable<Version>
in an obvious way. Parse all the strings to create a List<Version>
, then you can find the maximum value within the list (or sort the whole list). You could even just use the System.Version
class if you want, although that supports four parts when it looks like you only want three. If you don't mind it supporting more parts than you need, it would definitely be simpler than writing your own.
List<String> list = new List<String> { "1.0.0", "1.0.2", "1.1.0" };
List<Version> versions = list.Select(x => Version.Parse(x)).ToList();
Version maxVersion = versions.Max();
If you don't need any other versions, you don't even need the second list - just pass the projection into Max
:
List<String> list = new List<String> { "1.0.0", "1.0.2", "1.1.0" };
Version maxVersion = list.Max(x => Version.Parse(x));
Having the values parsed as Version
objects makes them much easier to work with than having them as strings. For example, you can trivially filter by major version number, or even "anything later than 1.0.5" or whatever you want to do. In general, it's a good idea to parse strings to a type that represents the data you're working with as early as possible, and only format it again as late as possible for display. This applies to strings, numbers, everything.