Better way to write this code

Started by
16 comments, last by HScottH 10 years, 1 month ago

Ah, good point. I didn't notice that the node it's self wasn't the coordinate....

As far as to whether or not it is better at this point is debatable.. but here's a Linq query to do it.

return nodes.Where(n => n.Number == number).Select(n => n.Coordinates).Cast<Coordinates?>().FirstOrDefault();

Advertisement

EDIT: Ignore, misunderstood question and code :/


[quote name='Paragon123']
Linq might work for you if nodes is IEnumerable.
[/quote]
Anything that you can foreach is IEnumerable, so it will definitely work.

Apparently its not working. "nodes" is a 2d array and the linq methods First and FirstOrDefault are not available for this array. However, I have checked that these methods are available for 1D arrays. Although I am able to traverse my 2D array using a foreach loop, I am not sure if the 2D arrays are part of Linq.Enumerable. I checked the msdn documentation but couldn't find anything specific relating to multidimensional arrays and these methods.

I have settled on this code though


public Coordinates? GetNodeCoordinates(int number)
        {
            Coordinates? coords = null;
            foreach(Node node in nodes)
            {
                if (node.Number == number)
                {
                    coords = node.Coordinates;
                    break;
                }
            }
            return coords; 
        }

I have enclosed the code that calls this function in a try block and if a null value is received, an exception is thrown and the situation is handled.

Apparently its not working. "nodes" is a 2d array


Ahh, I see. The primary set of LINQ methods work with IEnumerable<T>. 2D arrays appear to only implement IEnumerable but not the generic version of the interface. That's kind of strange considering the array rank doesn't affect whether it's homogenous or not...

In that case, you could add one more step if you REALLY wanted to do it this way:


return nodes
    .Cast<Node>() // Quick way to convert from IEnumerable to IEnumerable<Node>
    .Where(n => n.Number == number)
    .Select(n => n.Coordinates)
    .Cast<Coordinates?>()
    .FirstOrDefault();
(Personally, that's a lot of LINQ for such a simple operation. I would stick with the foreach loop.)

Thanks Nypren, but yeah I'm sticking with that code. I found this link http://stackoverflow.com/questions/275073/why-do-c-sharp-multidimensional-arrays-not-implement-ienumerablet that basically explains why 2D arrays can't use linq for anyone that is interested.

Thanks to everyone that helped. Cheers.

The proper course of action for code that should never be reached is to throw an exception, not return a random/meaningless value. Returning a nullable value, including all the hassle that will add to other parts of your code, for a section of code that SHOULD NEVER BE REACHED is damn stupid.


public Coordinates GetNodeCoordinates(int number)
{ 
    foreach(Node node in nodes)
    {
        if (node.Number == number)
        {
            coords = node.Coordinates;
            return coords;
        }
    }
    throw new InvalidOperationException(string.Format("Expected to find a node with number: {0}, but instead found nothing", number));
}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

The proper course of action for code that should never be reached is to throw an exception, not return a random/meaningless value. Returning a nullable value, including all the hassle that will add to other parts of your code, for a section of code that SHOULD NEVER BE REACHED is damn stupid.

This!

An exception is self-documenting of the fact that the code should never be reached and it will be "in your face" should the assumption that it never runs ever change, thereby alerting you to the problem.

HScottH, sorry for down voting you, I meant to up vote you, but my fat fingers pressed in wrong placed.

No worries; I'm sure I have deserved it other times where people were just too busy to "act."

I don't care about rep; it's chatting with my fellow geeks like you that makes this site good for me.

This topic is closed to new replies.

Advertisement