How can I put the index number as a value in a foreach?
I have the following code:
foreach (var SubTopic in Model开发者_运维知识库.SubTopic.Description)
{
<option value="xxx">SubTopic</option>
}
I would like to find a way to insert the index number into xxx as value. 01 for the first, 02 for the second option line etc.
Is there an easy way to do this?
Use a for loop like
for (int i = 0; i < Model.SubTopic.Description.Count; i++)
<option value="i">Model.SubTopic.Description[i]</option>
In C# you cannot directly access the actual index from within a foreach loop.
declare a variable with initial value 0 outside the loop and increment it inside the loop.
I am going to assume that the collection has no facility for retrieving items by index (like List
) otherwise you would have used a simple for
loop.
The foreach
construct has no builtin mechanisms for doing this, but it is easy enough to accomplish with a helper class.
foreach (var item in ForEachHelper.WithIndex(Model.SubTopic.Description))
{
Console.WriteLine("<option value=\"" + item.Index.ToString("00") + "\">" + item.Value + "</option");
}
And here is what the helper class looks like.
public static class ForEachHelper
{
public sealed class Item<T>
{
public int Index { get; set; }
public T Value { get; set; }
public bool IsLast { get; set; }
}
public static IEnumerable<Item<T>> WithIndex<T>(IEnumerable<T> enumerable)
{
Item<T> item = null;
foreach (T value in enumerable)
{
Item<T> next = new Item<T>();
next.Index = 0;
next.Value = value;
next.IsLast = false;
if (item != null)
{
next.Index = item.Index + 1;
yield return item;
}
item = next;
}
if (item != null)
{
item.IsLast = true;
yield return item;
}
}
}
精彩评论