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);
You probably don’t have to write a custom comparer. If all your labels are in the form
number.letter, you could use this.If you need more control, you could always convert the sortby fields (
aandb) to the appropriate types rather than ints and strings.If this is LINQ-to-SQL, this actually won’t work since some methods used here are not supported. Here’s a LINQ-to-SQL friendly version. It won’t yield the prettiest query, but it will work.