The question seems to be missing an important constraint in case there are repeating elements in the input collection that satisfy the condition given. Therefore, there is an assumption around the solutions provided that we are interested in the first encounter only.
How about a more general approach to return an IEnumerable collection so that the caller can decide what to take out of that such as the first, the last or the nth, etc.
private static IEnumerable<object> Find(object[] array)
{
if (array == null) throw new ArgumentNullException(nameof(array));
object previous = null;
foreach (var current in array)
{
if (Predicate(current)) yield return previous;
previous = current;
}
}
private static bool Predicate(object o)
{
return o != null && (int)o == 2;
}
There is also a null check for the input to fail fast. Predicate logic is irrelevant here.
Following is the test cases for the Find method:
[Test]
public void TestFind()
{
var items = Find(new object[] { 1, 2, 5, 2, 10, 2, 100, 2 });
Assert.AreEqual(1, items.First());
items = Find(new object[] { 0, 1, 1, 1, 1, 1 });
Assert.IsEmpty(items);
Assert.Throws<ArgumentNullException>(() => Find(null).ToList());
}
object foo;
as a non-valid data-placeholder, I have a new approach but I hate it even more:return array.Select((t, i) => Condition(t) ? i == 0 ? null : array[i - 1] : foo).First(e => e != foo);
\$\endgroup\$ – Markus May 27 '14 at 21:28