Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move item up in IEnumerable

Tags:

c#

ienumerable

I have a need to move an item in an IEnumerable<> up, that is move one item above another. What is the simplest way to do this?

A similar question was asked here but I don't have a generic list only an IEnumerable<>: Generic List - moving an item within the list

like image 412
Nina Avatar asked Jan 27 '26 20:01

Nina


2 Answers

As @Brian commented the question is a little unclear as to what move an item in an IEnumerable<> up means.

If you want to reorder an IEnumerable for a single item then the code below should might be what you are looking for.

public static IEnumerable<T> MoveUp<T>(this IEnumerable<T> enumerable, int itemIndex)
{
    int i = 0;

    IEnumerator<T> enumerator = enumerable.GetEnumerator();
    while (enumerator.MoveNext())
    {
        i++;

        if (itemIndex.Equals(i))
        {
            T previous = enumerator.Current;

            if (enumerator.MoveNext())
            {
                yield return enumerator.Current;
            }

            yield return previous;

            break;
        }

        yield return enumerator.Current;
    }

    while (enumerator.MoveNext())
    {
        yield return enumerator.Current;
    }
}
like image 84
Kane Avatar answered Jan 29 '26 10:01

Kane


You can't. IEnumerable is only to iterate through some items, not for editing a list of items

like image 30
remi bourgarel Avatar answered Jan 29 '26 10:01

remi bourgarel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!