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++);
}
}
精彩评论