How can I access the next value in a collection inside a foreach loop in C#?
I'm working in C# and with a sorted List<T>
of structs. I'm trying to iterate through the List
and for each iteration I'd like to acce开发者_StackOverflowss the next member of the list. Is there a way to do this?
Pseudocode example:
foreach (Member member in List)
{
Compare(member, member.next);
}
You can't. Use a for instead
for(int i=0; i<list.Count-1; i++)
Compare(list[i], list[i+1]);
You could just keep the previous value instead:
T prev = default(T);
bool first = true;
foreach(T item in list) {
if(first) {
first = false;
} else {
Compare(prev, item);
}
prev = item;
}
If one were so inclined, you could probably write an Extension method for this as well...
public static void ForEachNext<T>(this IList<T> collection, Action<T, T> func)
{
for (int i = 0; i < collection.Count - 1; i++)
func(collection[i], collection[i + 1]);
}
Usage:
List<int> numList = new List<int> { 1, 3, 5, 7, 9, 11, 13, 15 };
numList.ForEachNext((first, second) =>
{
Console.WriteLine(string.Format("{0}, {1}", first, second));
});
Use a regular for loop with an index, and compare list[i] and list[i+1]. (But make sure to only loop until the second-to-last index.)
Or, if you really want to use a foreach, you can keep a Member reference to the previous member and check the next time around. But I wouldn't recommend it.
LINQ might be your friend here. This approach will work with anything that's IEnumerable<T>, not just IList<T> collections, which is very useful if your collection never ends or is otherwise calculated on-the-fly:
class Program {
static void Main(string[] args) {
var list = new List<Int32> { 1, 2, 3, 4, 5 };
foreach (var comparison in list.Zip(list.Skip(1), Compare)) {
Console.WriteLine(comparison);
}
Console.ReadKey();
}
static Int32 Compare(Int32 first, Int32 second) {
return first - second;
}
}
XmlNode root = xdoc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("descendant::create-backup-sets/new-file-system-backup-set");
for (int j = 0; j < nodeList.Count; j++ )
{
for (int i = 0; i <= nodeList.Item(j).ChildNodes.Count - 1; i++)
{
if (nodeList.Item(j).ChildNodes[i].Name == "basic-set-info")
{
if (nodeList.Item(j).ChildNodes[i].Attributes["name"].Value != null)
{
// retrieve backup name
_bName = nodeList.Item(j).ChildNodes[i].Attributes["name"].Value.ToString();
}
}
You can do it by IndexOf but FYI IndexOf get the first item equal to the item so if you have a lot of items with the same value it's better to use for loop instead or define the range of search. Official docs are here
foreach (Member member in List)
{
var nextItem = List[List.IndexOf(member)+1];
Compare(member, nextItem);
}
精彩评论