sort a List<int> in c# ignoring the sign -
i have list below var initial = new list { 2, 5, 6,-1, -3, -4 };
expected output {-1,2,-3,-4,5,6} =>(sort given list ignoring -ve sign not removing them in result.)
my attempt solve
var initial = new list<string> { 2, 5, 6,-1, -3, -4 }; var dummylist = initial.findall(x => x < 0); initial .removeall(x => dummylist.contains(x)); foreach (var e in dummylist) { initial .add(e * -1); } initial.sort(); foreach (var e in dummylist) { var index = initial.findindex(x=>x==(e*-1)); initial.removeat(index); initial.insert(index, e); }
can give better solution this. https://dotnetfiddle.net/gcd1i1 thanks!
you can pass comparison
sort
method, compare using absolute value:
list.sort((a, b) => math.abs(a).compareto(math.abs(b)));
or using linq:
list = list.orderby(x => math.abs(x)).tolist();
Comments
Post a Comment