Reputation: 3100
So I have a class that contains a property called myNumber. It looks like this:
public class MyThing
{
public int name{ get; set; }
public string myNumber{ get; set; }
}
The value contained in myNumber can look like this 12-24
or 12-024
.
I would like to order a collection of these objects (IEnumerable<MyThing> myCollection
) by myNumber descending but I am not sure how to go about doing this.
I tried myCollection.OrderByDescending(f => f.myNumber)
but its not quite what I was expecting. I would expect 12-22, 13-01, 12-030
to order like this:
13-01
12-030
12-22
Upvotes: 1
Views: 68
Reputation: 460208
You can order it like a Version
. Therefore you can split by '-'
and use the first part as major- and the last part as minor version:
var orderedLikeVersion = myCollection
.Select(t => new
{
Thing = t,
Parts = t.myNumber.Split('-')
}).Select(x => new
{
x.Thing,
Version = new Version(int.Parse(x.Parts[0]), int.Parse(x.Parts[1]))
})
.OrderByDescending(x => x.Version)
.Select(x => x.Thing);
Demo with your desired result.
Upvotes: 2
Reputation: 38364
I'm guessing you got this order?
13-01
12-22
12-030
This would be correct by alphabetic conventions. 12-2* is greater than 12-0* since 2 comes after 0.
It also seems correct by numeric conventions, since 22 is also greater than 03, and 2 is greater than 0.
So I'm not sure in your expected ordering, why you interpret 12-030 as being greater than 12-22? Is the part after the hyphen supposed to allow leading zeros to be truncated? If you did that, then 12-30 would equal 12-030 and I would ask myself, what is the purpose of the leading 0.
Upvotes: 0