I have a query in linqtosql that returns a LabelNumber:
var q = from list in db.Lists
select list.LabelNumber;
var q
then becomes an IEnumerable<string>
with elements like this:
{"1","2","2.A","2.B","3","3.A","3.B"}
I basically want to order the elements as they appear above, but I can't use the OrderBy(x=>x.LabelNumber)
because "10"
would get placed after "1"
and before "2"
.
I assume I have to write a custom comparator function, but how do I do this with linq?
Edit: I think all of the answers below will work, but one caveat must be added to all responses.
If you are using Linq2SQL you cannot use array indexes within the query. To overcome this, you should have two queries. One that reads from SQL. The second does the ordering:
var q = from list in db.Lists
select list.LabelNumber;
var q2 = q.AsEnumerable()
.OrderBy(x => int.Parse(x.LabelNumber.Split('.')[0]))
.ThenBy(x => x.Number
.Contains(".") ?
x.LabelNumber.Split('.')[1].ToString()
:
string.Empty);