I have an array statsname as
apple
X
banana
Y
Kiwi
z
I need to put apple,banana and Kiwi in an array Fruits and X,Y and Z in an array calle
You could make an iterator which just skips every other element. The idea is to have a "view" of a collection, special enumerable which will return only some of the elements:
static IEnumerable everyOther( IEnumerable collection )
{
using( var e = collection.GetEnumerator() ) {
while( e.MoveNext() ) {
yield return e.Current;
e.MoveNext(); //skip one
}
}
}
You can use System.Linq.Skip to skip the first element.
string[] words = "apple X banana Y Kiwi z".Split();
var fruits = everyOther( words );
var alphabets = everyOther( words.Skip(1) );
Just use them as a new collection or call .ToArray()
or .ToList()
on them:
foreach( string f in fruits )
Console.WriteLine( f );
string[] anArray = fruits.ToArray(); //using System.Linq
Now you have what you need.
Iterators are methods which yield return
, see Iterators (C# Programming Guide). This is very strong feature of the language. You can: