Sunday, November 22, 2009

LINQ is awesome

So, after some prodding at work, I learned enough LINQ to be dangerous. Boy, it makes some code shorter and easier to read.

From:
public bool Operate(Character characterOperating, Point pointToOperateAt)
{
bool didAnything = false;

foreach (MapObject obj in m_map.MapObjects)
{
OperableMapObject operateObj = obj as OperableMapObject;
if (operateObj != null && operateObj.Position == pointToOperateAt)
{
operateObj.Operate();
m_timingEngine.ActorDidAction(characterOperating);
didAnything = true;
}
}

return didAnything;
}


To:
public bool Operate(Character characterOperating, Point pointToOperateAt)
{
    OperableMapObject operateObj = m_map.MapObjects.OfType<OperableMapObject>().
SingleOrDefault(x => x.Position == pointToOperateAt);
    if (operateObj != null)
    {
        operateObj.Operate();
        m_timingEngine.ActorDidAction(characterOperating);
        return true;
    }
    return false;
}

It doesn't seem like a lot, but multiple it a few dozen times and you get some serious space savings. It also helped me realize that the previous code was allowing for multiple map objects in a given square, which violates one of my map invariants.

No comments: