简体   繁体   English

在foreach循环中向前跳过C#

[英]skip ahead in a foreach loop c#

if I have a foreach loop that takes a whole bunch of addresses and loops through them, is there a way I could skip the first 500 entries, 如果我有一个foreach循环需要一大堆地址并循环通过它们,是否可以跳过前500个条目,

something like: 就像是:

foreach(var row in addresses)
{
  string strAddr = row.ADDRESS + "," + row.CITY + "," + row.ST;
  System.Threading.Thread.Skip(500)
}

I know skip doesn't exist but is there anything I can use that would do the same thing? 我知道skip不存在,但是有什么我可以使用的,可以做同样的事情吗?

You can use a method with a meaningful name: 您可以使用一个有意义的名称的方法

foreach(var row in addresses.Skip(500))
{
    // ...
}

You need to add using System.Linq; 您需要using System.Linq;添加using System.Linq; since it's a LINQ extension method. 因为它是LINQ扩展方法。

If the type of addresses doesn't implement the generic IEnumerable<T> interface you could use Cast<T> . 如果addresses类型未实现通用IEnumerable<T>接口,则可以使用Cast<T> For example (presuming the type is Address ): 例如(假设类型为Address ):

foreach(var row in addresses.Cast<Address>().Skip(500))
{
    // ...
}

You can use the Skip extension method: 您可以使用“ Skip扩展方法:

foreach(var row in addresses.Skip(500))
{
    string strAddr = row.ADDRESS + "," + row.CITY + "," + row.ST;
}

Or, if addresses is just an array or list: 或者,如果addresses只是数组或列表:

for (int i = 500 ; i < addresses.Count ; i++) // assuming addresses is a List<T>
{
    var row = addresses[i];
    string strAddr = row.ADDRESS + "," + row.CITY + "," + row.ST;
}

Use the Enumerator interface directly: http://msdn.microsoft.com/en-us/library/system.collections.ienumerator(v=vs.110).aspx 直接使用Enumerator界面: http : //msdn.microsoft.com/zh-cn/library/system.collections.ienumerator(v=vs.110).aspx

var enumerator = addresses.GetEnumerator();
for (var i = 0; i < 300 && enumerator.MoveNext(); i++);

A feasible and fast solution would be to use LINQ Skip method to iterate over a subset of the collection starting from the 500th element of the collection. 一种可行且快速的解决方案是使用LINQ Skip方法从集合的第500个元素开始迭代集合的子集。

foreach (var row in addresses.Skip(500))
{
   // do your stuff...
}

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

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