IList<Object> collection = new List<Object> {new Object(),new Object(),new Object(),};
foreach (Object o in collection){Console.WriteLine(collection.IndexOf(o));}
Console.ReadLine();
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action){var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a voidenumerable.Select((item, i) =>{action(item, i);return unit;}).ToList();
return pSource;}
var destinationList = new List<someObject>();foreach (var item in itemList){var stringArray = item.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (stringArray.Length != 2){//use the destinationList Count property to give us the index into the stringArray listthrow new Exception("Item at row " + (destinationList.Count + 1) + " has a problem.");}else{destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]});}}
<%int i=0;foreach (var review in Model.ReviewsList) { %><div id="review_<%=i%>"><h3><%:review.Title%></h3></div><%i++;} %>
你可以这样写:
<%foreach (var review in Model.ReviewsList.WithIndex()) { %><div id="review_<%=LoopHelper.Index()%>"><h3><%:review.Title%></h3></div><%} %>
我写了一些辅助方法来实现这一点:
public static class LoopHelper {public static int Index() {return (int)HttpContext.Current.Items["LoopHelper_Index"];}}
public static class LoopHelperExtensions {public static IEnumerable<T> WithIndex<T>(this IEnumerable<T> that) {return new EnumerableWithIndex<T>(that);}
public class EnumerableWithIndex<T> : IEnumerable<T> {public IEnumerable<T> Enumerable;
public EnumerableWithIndex(IEnumerable<T> enumerable) {Enumerable = enumerable;}
public IEnumerator<T> GetEnumerator() {for (int i = 0; i < Enumerable.Count(); i++) {HttpContext.Current.Items["LoopHelper_Index"] = i;yield return Enumerable.ElementAt(i);}}
IEnumerator IEnumerable.GetEnumerator() {return GetEnumerator();}}
//var list = new List<int> { 1, 2, 3, 4, 5, 6 }; // Your sample collection
var listEnumerator = list.GetEnumerator(); // Get enumerator
for (var i = 0; listEnumerator.MoveNext() == true; i++){int currentItem = listEnumerator.Current; // Get current item.//Console.WriteLine("At index {0}, item is {1}", i, currentItem); // Do as you wish with i and currentItem}
var listOfNames = new List<string>(){"John","Steve","Anna","Chris"};
var listCount = listOfNames.Count;
var NamesWithCommas = string.Empty;
foreach (var element in listOfNames){NamesWithCommas += element;if(listOfNames.IndexOf(element) != listCount -1){NamesWithCommas += ", ";}}
NamesWithCommas.Dump(); //LINQPad method to write to console.
// Hope the JIT compiler optimises read of the 'Count' property!for (var i = 0; i < collection.Count; i++) {var e = collection[i];// Do stuff with 'e' and 'i'}
// First, filter 'e' based on 'i',// then apply an action to remaining 'e'collection.AsParallel().Where((e,i) => /* filter with e,i */).ForAll(e => { /* use e, but don't modify it */ });
// Using 'e' and 'i', produce a new collection,// where each element incorporates 'i'collection.AsParallel().Select((e, i) => new MyWrapper(e, i));
var s = "ABCDEFG";foreach (var item in s.GetEnumeratorWithIndex()){System.Console.WriteLine("Character: {0}, Position: {1}", item.Value, item.Index);}
添加以下struct和扩展方法后。
struct和扩展名方法封装了枚举。选择功能。
public struct ValueWithIndex<T>{public readonly T Value;public readonly int Index;
public ValueWithIndex(T value, int index){this.Value = value;this.Index = index;}
public static ValueWithIndex<T> Create(T value, int index){return new ValueWithIndex<T>(value, index);}}
public static class ExtensionMethods{public static IEnumerable<ValueWithIndex<T>> GetEnumeratorWithIndex<T>(this IEnumerable<T> enumerable){return enumerable.Select(ValueWithIndex<T>.Create);}}
foreach (var (item, index) in collection.WithIndex()){Debug.WriteLine($"{index}: {item}");}
需要一点扩展方法:
using System.Collections.Generic;
public static class EnumExtension {public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)=> self.Select((item, index) => (item, index));}
Microsoft C#语言开发团队可以通过添加对新接口IIndexedENumable的支持来创建新的C#语言功能
foreach (var item in collection with var index){Console.WriteLine("Iteration {0} has value {1}", index, item);}
//or, building on @user1414213562's answerforeach (var (item, index) in collection){Console.WriteLine("Iteration {0} has value {1}", index, item);}
如果使用foreach ()并且存在with var index,则编译器期望项集合声明IIndexedEnumerable接口。如果接口不存在,编译器可以用IndexedENumable对象填充源,这会添加跟踪索引的代码。
interface IIndexedEnumerable<T> : IEnumerable<T>{//Not index, because sometimes source IEnumerables are transientpublic long IterationNumber { get; }}
static class Extensions{public static IEnumerable<(int, T)> Enumerate<T>(this IEnumerable<T> input,int start = 0){int i = start;foreach (var t in input){yield return (i++, t);}}}
class Program{static void Main(string[] args){var s = new string[]{"Alpha","Bravo","Charlie","Delta"};
foreach (var (i, t) in s.Enumerate()){Console.WriteLine($"{i}: {t}");}}}
//// Summary:// Exposes an enumerator, which supports a simple iteration over a non-generic collection.public interface IEnumerable{//// Summary:// Returns an enumerator that iterates through a collection.//// Returns:// An System.Collections.IEnumerator object that can be used to iterate through// the collection.IEnumerator GetEnumerator();}
//// Summary:// Supports a simple iteration over a non-generic collection.public interface IEnumerator{//// Summary:// Gets the element in the collection at the current position of the enumerator.//// Returns:// The element in the collection at the current position of the enumerator.object Current { get; }
//// Summary:// Advances the enumerator to the next element of the collection.//// Returns:// true if the enumerator was successfully advanced to the next element; false if// the enumerator has passed the end of the collection.//// Exceptions:// T:System.InvalidOperationException:// The collection was modified after the enumerator was created.bool MoveNext();//// Summary:// Sets the enumerator to its initial position, which is before the first element// in the collection.//// Exceptions:// T:System.InvalidOperationException:// The collection was modified after the enumerator was created.void Reset();}