HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Take previous element from array if condition on current element matches

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
matchespreviousconditionarraytakeelementcurrentfrom

Problem

Any ideas to simplify this beauty; I would prefer a LinQ expression if possible:

private object[] array;
public abstract bool Condition(object o);
//...
private object FindStuff()
{
    for (int i = 0; i < array.Length; i++)
    {
        if (Condition(array[i]))
        {
            return i == 0 ? null : array[i-1];
        }
    }
    throw new ItemNotFoundException();
}
//...

Solution

This code would benefit from a previous variable...... and it would also benefit from being real code, not this hypothetical example..... This code is also really short, so it's hard to simplify more.

Still, using a foreach is better than the indexed iterator, and the logic is more obvious with named variables, rather than indexes... so:

private object[] array;
public abstract bool Condition(object o);
//...
private object FindStuff()
{
    object previous = null;
    foreach (object current in array)
    {
        if (Condition(current))
        {
            return previous;
        }
        previous = current;
    }
    throw new ItemNotFoundException();
}

Code Snippets

private object[] array;
public abstract bool Condition(object o);
//...
private object FindStuff()
{
    object previous = null;
    foreach (object current in array)
    {
        if (Condition(current))
        {
            return previous;
        }
        previous = current;
    }
    throw new ItemNotFoundException();
}

Context

StackExchange Code Review Q#51860, answer score: 11

Revisions (0)

No revisions yet.