I got this code in asp.net mvc3 controller for view and order in a dropdown. But my problem is as you can see in the picture below it order by
text and next to it the number
ViewBag.AddrBarangay = new SelectList(db.Barangays, "BarangayId", "BarangayName", "").OrderBy(m => m.Text);
For your case, you have to create new Comparer which can sort in lexicograhical order
You should have your own implementation of comparer which implements IComparer<string>
interface. Your comparer should be like this :
public class LexicoComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var firstArgumentSplits = x.Split(' ');
var secondArgumentSplits = y.Split(' ');
if (firstArgumentSplits.Length == 2 && secondArgumentSplits.Length == 2)
{
int firstArgumentInt, secondArgumentInt;
if (firstArgumentSplits[0] == secondArgumentSplits[0])
{
if (int.TryParse(firstArgumentSplits[1], out firstArgumentInt))
{
if (int.TryParse(secondArgumentSplits[1], out secondArgumentInt))
{
return firstArgumentInt == secondArgumentInt ? 0 : firstArgumentInt > secondArgumentInt ? 1 : 0;
}
}
}
}
return String.Compare(x, y);
}
}
Now you use above comparer in OrderBy
:
ViewBag.AddrBarangay = new SelectList(db.Barangays,
"BarangayId", "BarangayName", "").OrderBy(m => m.Text,
new LexicoComparer());