Looping through 2 Lists at once

前端 未结 7 458

I have two lists that are of the same length, is it possible to loop through these two lists at once?

I am looking for the correct syntax to do the below



        
7条回答
  •  庸人自扰
    2021-01-31 11:21

    I had this same problem but using lists of objects with lists inside of them.. for what its worth, this might help someone with the same issue.

    The running time of this isn't very good since IndexOf is O(n), but at the time, I'm dealing with a lot more inner-foreach loops than in this example, so I didn't want to deal with handling iterator variables.

    At times like this I very much miss PHPs foreach($arrayList as $key => $value) notation... maybe I'm missing something in C#, there's got to be a way to get the index in O(c) time! (sadly this post says no: Getting the array key in a 'foreach' loop)

    class Stock {
       string symbol;
       List hourlyPrice; // provides a list of 24 decimals
    }
    
    // get hourly prices from yesterday and today
    List stockMondays = Stocks.GetStock("GOOGL,IBM,AAPL", DateTime.Now.AddDay(-1));
    List stockTuesdays = Stocks.GetStock("GOOGL,IBM,AAPL", DateTime.Now);
    
    try {
        foreach(Stock sMonday in stockMondays) {
            Stock sTuesday = stockTuesday[stockMondays.IndexOf(sMonday)];
    
            foreach(decimal mondayPrice in sMonday.prices) {
                decimal tuesdayPrice = sTuesday.prices[sMonday.prices.IndexOf(mondayPrice)];
                // do something now
            }
    
        }
    } catch (Exception ex) { // some reason why list counts aren't matching? }
    

提交回复
热议问题