如何在C Sharp中的每个循环中跳过A中的特定位置? [英] How to skip a specific position within a for each loop in c sharp?

查看:83
本文介绍了如何在C Sharp中的每个循环中跳过A中的特定位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<string> liste = new List<String> 
        {
            "A","B","C","D"
        };

        foreach (var item in liste)
        {
            System.Diagnostics.Debug.WriteLine(item.ToString());
        }

        for (int i = 0; i < liste.Count; i++)
        {
            if (i == 0)
                continue;
            System.Diagnostics.Debug.WriteLine(liste[i].ToString());
        }

如何跳过foreach循环中的特定位置?我不想评估任何值,而只是跳过位置x.

How do i skip a specific position in a foreach loop? I do not want to evaluate any values, but just skip the position x.

它必须是一个特定的位置.一个人可以选择位置0,也可以选择位置7.

It has to be a specific position. One could choose position 0 or maybe position 7.

推荐答案

跳过列表中的第一项非常容易:

It is very easy to skip the first item in the list:

foreach(var item in list.Skip(1))
{
    System.Diagnostics.Debug.WriteLine(item.ToString());
}

如果您要跳过索引 n 处的任何其他元素,则可以这样编写:

If you want to skip any other element at index n, you could write this:

foreach(var item in list.Where((a,b) => b != n))
{
    System.Diagnostics.Debug.WriteLine(item.ToString());
}

在此示例中,我使用带有两个参数的lambda表达式: a b .参数 a 是项目本身,而参数 b 是项目的索引.

In this example I use a lambda expression that takes two arguments: a and b. Argument a is the item itself, while argument b is the index of the item.

MSDN上描述这些扩展方法的相关页面是:

The relevant pages on MSDN that describe these extension methods are:

您甚至可以编写自己的扩展方法,使您可以跳过列表中的元素:

You could even write your own extension method that allows you to skip an element in a list:

public static class MyEnumerableExtensions
{
    public static IEnumerable<T> SkipAt<T>(this IEnumerable<T> list, int index)
    {
        var i = 0;

        foreach(var item in list) 
        {
            if(i != index)
                yield return item;

            i++;
        }
    }
}

这将使您可以编写类似这样的内容来跳过项目:

This will allow you to write something like this to skip an item:

foreach(var item in list.SkipAt(2))
{
    System.Diagnostics.Debug.WriteLine(item.ToString());
}

这篇关于如何在C Sharp中的每个循环中跳过A中的特定位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆