c# - Sort a List and keep a particular element at end of list after sorting -
i have list of string containing "others". getting list drop down. sorting list alphabetically. need "others" @ end of list. don't want add element after sorting 1 solution. there other way same using custom comparer of .sort() method. tried below no solution.
public class eocomparer : icomparer<string> { public int compare(string x, string y) { if (x == null) { if (y == null) { // if x null , y null, they're // equal. return 0; } else { // if x null , y not null, y // greater. return -1; } } else { // if x not null... // if (y == null) // ...and y null, x greater. { return 1; } else { if (x.tolower().contains("other")) { return -1; } else { // if strings of equal length, // sort them ordinary string comparison. // return x.compareto(y); } } } } and calling :
eocomparer c = new eocomparer(); a.sort((x, y) => c.compare(x.optionvalue, y.optionvalue)); return a; please if possible.
this fine answer, thought fix comparer:
test:
[testcase(new string[0], new string[0])] [testcase(new[] { "a" }, new[] { "a" })] [testcase(new[] { "a", "b" }, new[] { "a", "b" })] [testcase(new[] { "b", "a" }, new[] { "a", "b" })] [testcase(new[] {"others"}, new[] {"others"})] [testcase(new[] {"a", "others"}, new[] {"a", "others"})] [testcase(new[] {"others", "a"}, new[] {"a", "others"})] [testcase(new[] {"others", "x"}, new[] {"x", "others"})] [testcase(new[] {"others", "x"}, new[] {"x", "others"})] [testcase(new[] { "othersz", "others" }, new[] { "othersz", "others" })] [testcase(new[] {"z", "y", "x", "others", "b", "a", "c"}, new[] {"a", "b", "c", "x", "y", "z", "others"})] public void cansortwithothersatend(string[] input, string[] expectedsorted) { var = new list<string>(input); var c = new eocomparer(); a.sort(c.compare); collectionassert.areequal(expectedsorted, a); } comparer:
public sealed class eocomparer : icomparer<string> { public int compare(string x, string y) { if (isothers(x)) return 1; if (isothers(y)) return -1; return string.compare(x, y, stringcomparison.ordinal); } private static bool isothers(string str) { return string.compare(str, "others", stringcomparison.ordinalignorecase) == 0; } } note how use of string.compare avoids == null checks. , how stringcomparison.ordinalignorecase avoids .tolower() , avoids creating copies of strings.
Comments
Post a Comment