0

I've got this piece of code to get the next value using LINQ namespace.

public static class Extension
{
    public static T Next<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        bool flag = false;

        using (var enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                if (flag) return enumerator.Current;

                if(predicate(enumerator.Current))
                {
                    flag = true;
                }
            }
        }
        return default(T);
    }
}

But now, I need also to get the previous value, but I here I do not know what to do.

Darf Zon
  • 6,268
  • 20
  • 90
  • 149

3 Answers3

2
public static T Previous<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {       
        T t = default(T);
        using (var enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {   
                if(predicate(enumerator.Current))
                {
                    return t;
                }
                t = enumerator.Current;
            }
        }
        return default(T);
    }
Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73
2

I may be missing something here, but what's the reasoning behind directly accessing IEnumerable<T>.GetEnumerator(), IEnumerator<T>.MoveNext() and IEnumerator<T>.Current? Seems like you're directly replicating what the foreach loop does.

public static T Next<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    bool shouldReturn = false;
    foreach (var item in source)
    {
        if(shouldReturn)
            return item;

        if (predicate(item))
            shouldReturn = true;
    }
    return default(T);
}

public static T Previous<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    var previous = default(T);
    foreach (var item in source)
    {
        if (predicate(item))
            return previous;
        previous = item;
    }
    return default(T);
}
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
1

If you only need the immediately preceding value, why not just hang on to each "previous" as you iterate through the collection. If you need a more complex iterator, check out this SO post.

Community
  • 1
  • 1
Adam S
  • 3,065
  • 1
  • 37
  • 45