Custom sort logic in OrderBy using LINQ
Posted
by Bala R
on Stack Overflow
See other posts from Stack Overflow
or by Bala R
Published on 2010-06-09T15:47:10Z
Indexed on
2010/06/09
16:32 UTC
Read the original article
Hit count: 215
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;
}
}
© Stack Overflow or respective owner