开发者

Custom Linq Extension to replace For loop

public static void For<T>(this IEnumerable<T> items, Action<T, int> predicate)
    {
        using (IEnumerator<T> iterator = items.GetEnumerator())
        {
            int index = 0;
            while (iterator.MoveNext())
            {
                T item = iterator.Current;
                predicate(item, index);
                index++;
            }
        }
    }开发者_JS百科 

I'm intesting in a linq extention to enumerate over a list and perform an action with the index of the collection - like a for loop.

then you can use the method like this

items.For((item, index) => item.Prop = item.Prop != MyMethod(index) ? MyMethod(index) : item.Prop);

Does this seem right?


Try this:

public static void For<T>(this IEnumerable<T> items, Action<T, int> predicate)
{
    int i=0;
    foreach (T item in items)
    {
        predicate(item, i++);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜