3

I have a slight problem with this code:

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

This works fine if I want every object to print.

I was wondering if I could exclude the first item in the array? So it would only output "Word 2". I know the obvious solution is not to include the first item but in this case I can't.

Bali C
  • 30,582
  • 35
  • 123
  • 152

4 Answers4

8

Using LINQ to Objects, you can just use Skip:

foreach (string word in words.Skip(1))
{
    Console.WriteLine(word);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
8

Using LINQ in .Net 3.5 and up:

string[] words = {"Word 1", "Word2"}
foreach (string word in words.Skip(1))
{  
    Console.WriteLine(word);
}

Note that you must have a using System.Linq; statement at the top of your file, as Skip is an extension method.

An alternative option is to use a regular for loop:

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

I also strongly discourage the use of Hungarian-like prefixes in variable names in .Net.

Sven
  • 21,903
  • 4
  • 56
  • 63
  • Ok, thanks, why would you advice not to use these variable names? – Bali C Jul 19 '11 at 12:17
  • @Bali: They add no value (the type of the variable indicates that it's a string array) and just make it harder to read the code. – Jon Skeet Jul 19 '11 at 12:18
  • @Bali C: http://stackoverflow.com/questions/111933/why-shouldnt-i-use-hungarian-notation – Yuck Jul 19 '11 at 12:19
  • 1
    Because common style guidelines for C# encourage you not to use Hungarian notation. Hungarian notation also encodes sometimes unnecessary type information in the names, which can make refactoring the code more difficult (as you'd have to change the names if you change the type). – Sven Jul 19 '11 at 12:19
7

You can use a for loop instead:

string[] sWords = {"Word 1", "Word2"};
var len = sWords.Length;

for (int i = 1; i < len; i++)
{
  Console.WriteLine(sWords[i]);
}
FIre Panda
  • 6,537
  • 2
  • 25
  • 38
Yuck
  • 49,664
  • 13
  • 105
  • 135
3

You could do

string[] sWords = {"Word 1", "Word2"};

 for(int i=1; i<sWords.Length; i++) 
 {   
   Console.WriteLine(sWord[i]); 
 } 
FIre Panda
  • 6,537
  • 2
  • 25
  • 38