c# - Implementing custom IComparer<> (with example) -
ive written next code, order strings native string.compare()
allow collection of exceptions (in case custompriority
) place priority on default string.compare()
function.
it seems bit long winded, wondering if there built .net allow this?
var unorderered = new[] { "a", "b", "c", "x", "y", "z" }; var ordered = unorderered.orderby(a => a, new customstringcomparer()); //expected order y,x,a,b,c,z class customstringcomparer : icomparer<string> { int icomparer<string>.compare(string x, string y) { if (x == y) homecoming 0; else { //---------------------------- //beginning of custom ordering var custompriority = new[] { "y", "x" }; if (custompriority.any(a => == x) && custompriority.any(a => == y)) //both in custom ordered array { if (array.indexof(custompriority, x) < array.indexof(custompriority, y)) homecoming -1; homecoming 1; } else if (custompriority.any(a => == x)) //only 1 item in custom ordered array (and x) homecoming -1; else if (custompriority.any(a => == y)) //only 1 item in custom ordered array (and y) homecoming 1; //--------------------------- //degrade default ordering else homecoming string.compare(x, y); } } }
first, think it's useful restate problem: want sort by:
the index in given array; if item not in array, index infinity the string itselfthat means can accomplish sort order using orderby()
first status followed thenby()
sec one:
private static uint negativetomaxvalue(int i) { if (i < 0) homecoming uint.maxvalue; homecoming (uint)i; } … var ordered = unorderered .orderby(a => negativetomaxvalue(array.indexof(new[] { "y", "x" }, a))) .thenby(a => a);
negativetomaxvalue()
necessary, because items not in array should last, first normally, because index -1. (a hackish , unreadable way same straight cast result of indexof()
uint
.)
if wanted reuse sorting creating icomparer
, believe there nil in .net help that. utilize comparerextensions instead:
icomparer<string> comparer = keycomparer<string> .orderby(a => negativetomaxvalue(array.indexof(new[] { "y", "x" }, a))) .thenby(a => a);
c# compare order icomparer
No comments:
Post a Comment