Reputation: 924
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
. How to fix this issue?.
ViewBag.AddrBarangay = new SelectList(db.Barangays, "BarangayId", "BarangayName", "").OrderBy(m => m.Text);
Upvotes: 1
Views: 89
Reputation: 16310
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());
Upvotes: 3
Reputation: 21815
Although IMHO the best way to solve this would be to store the values like 1,10,100
in SelectList value property and thensort it. If for some reason you can't do that then you need to provide the custom EqualityComparer in the OrderBy
clause.
Also, if your text Barangay
would always remain constant then you can do it this way as well (although not a very good approach as it's not generic):-
int maxSize = db.Barangays.Max(x => x.Text.Length);
ViewBag.AddrBarangay = new SelectList(db.Barangays, "BarangayId", "BarangayName", "")
.OrderBy(m => m.Text.Replace("Barangay","").Trim().PadLeft(maxSize ,'0'));
Upvotes: 2