I have a method like this:
public void DoSomething( .... , bool orderByX)
{
if(orderByX)
{
foreach( ... OrderBy(x => x.Location.X))
{
...
}
}
else
{
foreach( ... OrderBy(x => x.Location.Y)
{
...
}
}
}
I would like to avoid the if to produce less repetitive code (i.e. just one foreach). Is this possible?
Thanks.
A better approach, is to pass criteria, by which to order. You can use next code as motivation:
public void DoSomething<T>( .... , Func<Point, T> orderbySelector)
{
foreach( ... OrderBy(p => orderbySelector(p.Location)))
{
...
}
}
Now you can:
DoSomething(mySequence, point => point.X)
or
DoSomething(mySequence, point => point.Y)
Note: you can generalize selector as much as you want (for instance passing holder or Location
, instead of Point
itself).
Also, passing bool
as ordering criteria makes code less readable. For example I have no clue what this method does, by simply looking at it's call DoSomething(list, false)
and I have to see method signature in order to know what are the semantics of false
. It would be much better to use named parameters DoSomething(list, orderByX : false)
(available from C# 4.0), but if I'm not ordering by X
, how do I know, that I'm then ordering by Y
?. This also limits calling code only to two sorting criteria (you wouldn't want to add another sorting flag, wouldn't you?)
So you need to open your intention making DoSomething
name revealing, that you in fact ordering your processing. For example TraverseNodesOrderedBy(nodes, point => point.X)
Check orderByX
in the lambda expression for OrderBy
public void DoSomething( .... , bool orderByX)
{
foreach( ... OrderBy(x => orderByX ? x.Location.X : x.Location.Y))
{
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With