0

Does OrderBy(item => false) affect array order?

I want to move certain element to the end of the array:

var numbers = new[] { 3, 7, 4, 1, 5 };
var result = numbers.OrderBy(item => item == 4).ToArray();

Does this solution have any side effects affecting the order of other elements (!=4)?

Hopeless
  • 579
  • 1
  • 8
  • 25
  • 3
    What do you mean by "side effects"? This works because it's sorting by the numerical value of a bool, which is 0 for false and 1 for true, in .NET. Are you asking whether the order will be retained for items that are not 4? – CodeCaster Feb 27 '20 at 15:26
  • 2
    If your question is whether OrderBy is "stable", that is, retain the order for items with the same sort value, then see duplicate: yes. – CodeCaster Feb 27 '20 at 15:30
  • 1
    @CodeCaster - whilst that may be "true" for certain values of true, it's actually sorting because bool implements IComparable. Nothing to do with any (exposed) "numerical value" – Damien_The_Unbeliever Feb 27 '20 at 15:31
  • @Damien whoops, I may have confused a thing or two here, thanks for the clarification. – CodeCaster Feb 27 '20 at 15:32
  • @CodeCaster "Are you asking whether the order will be retained for items that are not 4?" - yes, exactly this – Hopeless Feb 27 '20 at 15:49

2 Answers2

1

No this is fine, results with true (4) will be at the end of the list, your result will be 3, 7, 1, 5, 4

PeterT
  • 269
  • 1
  • 2
  • 9
  • 2
    Just because something looks fine for a small sample doesn't mean it's fine in general. As the duplicate explains, `OrderBy` was explicitly implemented to be stable – Panagiotis Kanavos Feb 27 '20 at 15:32
0

There is no side effects, as OrderBy operates on IEnumerable which doesn't have any methods to mutate collection

Renat
  • 7,718
  • 2
  • 20
  • 34
  • This is true if you interpret "side effects" as "mutating the underlying collection". The OP probably means something else. – CodeCaster Feb 27 '20 at 15:28
  • From Wikipedia https://en.wikipedia.org/wiki/Side_effect_(computer_science) `has an observable effect besides returning a value (the main effect) to the invoker of the operation` , hence OP most probably means underlying collection, not the output sequence – Renat Feb 27 '20 at 15:31
  • 3
    I am not asking for an arbitrary definition, I'm asking what the OP means by it. There is no use in answering a guess. – CodeCaster Feb 27 '20 at 15:31
  • @CodeCaster, but question includes a term `side effect` – Renat Feb 27 '20 at 15:33