Custom sort logic in OrderBy using LINQ
- by Bala R
What would be the right way to sort a list of strings where I want items starting with an underscore '_', to be at the bottom of the list, otherwise everything is alphabetical.
Right now I'm doing something like this,
autoList.OrderBy(a => a.StartsWith("_") ? "ZZZZZZ"+a : a )
EDIT:
I ended up using something like this; optimization suggestions welcome!
private class AutoCompleteComparer : IComparer<String>
{
public int Compare(string x, string y)
{
if (x.StartsWith("_") && y.StartsWith("_") || (!x.StartsWith("_") && !y.StartsWith("_")))
{
return x.CompareTo(y);
}
else if (x.StartsWith("_"))
{
return 1;
}
else if (y.StartsWith("_"))
{
return -1;
}
return 0;
}
}