我对这段代码有些小问题:
string[] sWords = {"Word 1", "Word2"}
foreach (string sWord in sWords)
{
Console.WriteLine(sWord);
}
如果我想要打印每个对象,那么这很好用。
我想知道是否可以排除数组中的第一个项目?这样它只会输出“Word 2”。我知道显而易见的解决方案是不包括第一个项目,但在这种情况下我不能这样做。
使用LINQ to Objects,你可以只需使用Skip
:
foreach (string word in words.Skip(1))
{
Console.WriteLine(word);
}
在 .Net 3.5 及以上版本中使用 LINQ:
string[] words = {"Word 1", "Word2"}
foreach (string word in words.Skip(1))
{
Console.WriteLine(word);
}
using System.Linq;
语句,因为Skip
是一个扩展方法。for( int x = 1; x < words.Length; ++x )
Console.WriteLine(words[x]);
我也强烈反对.Net中变量名使用匈牙利式前缀。
string[] sWords = {"Word 1", "Word2"};
var len = sWords.Length;
for (int i = 1; i < len; i++)
{
Console.WriteLine(sWords[i]);
}
string[] sWords = {"Word 1", "Word2"};
for(int i=1; i<sWords.Length; i++)
{
Console.WriteLine(sWord[i]);
}