[英]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++);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.