Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

orderby certain property - code improvement

Tags:

c#

linq

c#-4.0

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.

like image 392
cs0815 Avatar asked Nov 30 '22 03:11

cs0815


2 Answers

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)

like image 159
Ilya Ivanov Avatar answered Dec 11 '22 04:12

Ilya Ivanov


Check orderByX in the lambda expression for OrderBy

public void DoSomething( .... , bool orderByX)
{
    foreach( ... OrderBy(x => orderByX ? x.Location.X : x.Location.Y))
    {
      ...
    }
}
like image 33
Ahmed KRAIEM Avatar answered Dec 11 '22 04:12

Ahmed KRAIEM