简体   繁体   English

C#识别for循环中的项目

[英]C# identifying items within a for loop

I've created a for loop that will be used to display 8 items per section, but I'm trying to identify certain items within the loop. 我创建了一个for循环,该循环将用于在每个节中显示8个项目,但是我正在尝试识别循环中的某些项目。 For instance I want to identify the first two items, then fifth and sixth but can seem to get my identification techniques correct. 例如,我想识别前两个项目,然后识别第五和第六个项目,但似乎可以使我的识别技术正确。

for (int i = 0; i < Model.Count; i++){
    var item = Model[i]
    if ((i + 1) % 3 != 0 && (i + 1) % 4 != 0){
        // What i want to display here
    }
    else{
        // Something else I want to display
    }
}

This kind of works for the first four items but for the last four items it doesn't seem to work 这种方法适用于前四项,但对于后四项似乎无效

for (int i = 0; i < Model.Count; i++){
    var item = Model[i]
    int aux = i%4;
    if (aux==0|| aux==1){
        // What i want to display here
    }
    else{
        // Something else I want to display
    }
}

Instead of messing around with modulo a 'cheap' trick is to just have a counter that keeps track of where you are and resets on each loop. 与其搞乱modulo ,“便宜”的窍门是拥有一个计数器来跟踪您的位置并在每个循环上重置,而不是“便宜”。

// Dummy list to represent whatever 'Model' is
var model = new List<string> { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve" };

// A counter that keeps track of whether we're on 1, 2, 5 or 6
var counter = 1;

// Your loop
for (int i = 0; i < model.Count; i++)
{
    // Get the item as you've shown
    var item = model[i];

    // Check whether we want this item or not
    if (counter == 1 || counter == 2 || counter == 5 || counter == 6)
    {
        // Display
        Console.WriteLine("Displayed: " + item);
    }
    else
    {
        // Do whatever else
        Console.WriteLine("Skipped: " + item);
    }

    // Increase the counter
    counter++;

    // Reset the counter if we're into the next batch of 8
    if (counter > 8)
        counter = 1;
}   

Output: 输出:

Displayed: one 显示:1
Displayed: two 显示:2
Skipped: three 跳过:三
Skipped: four 跳过:四
Displayed: five 显示:五个
Displayed: six 显示:六个
Skipped: seven 跳过:七
Skipped: eight 跳过:八
Displayed: nine 显示:九
Displayed: ten 显示:十
Skipped: eleven 跳过:十一
Skipped: twelve 跳过:十二

I admit it's not very 'fancy' but it works fine and is easy to understand. 我承认这不是很“花哨”,但效果很好并且易于理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM