c#排除数组对象

本文关键字:对象 数组 排除 | 更新日期: 2023-09-27 18:02:59

这段代码有一个小问题:

string[] sWords = {"Word 1", "Word2"}
foreach (string sWord in sWords)
{
  Console.WriteLine(sWord);
}

如果我想打印每个对象,这很好。

我想知道我是否可以排除数组中的第一项?所以它只会输出"Word 2"。我知道最明显的解决办法是不包括第一项,但在这种情况下我不能。

c#排除数组对象

使用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循环:

for( int x = 1; x < words.Length; ++x )
    Console.WriteLine(words[x]);

我也强烈建议在。net的变量名中使用类似匈牙利语的前缀。

您可以使用for循环:

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]); 
 }