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
using only Arrays
:
var array = new string[] { "apple", "X", "banana", "Y", "Kiwi", "z" };
var fruit = new string[array.Length];
var alphabet = new string[array.Length];
for(var i = 0,j = 0; i < array.Length / 2; i++, j += 2)
{
fruit[i] = array[j];
alphabet[i] = array[j + 1];
}
Stolen from How to get Alternate elements using Enumerable in C#
var fruits = myArray.Where((t, i) => i % 2 == 0).ToArray();
var alphabets = myArray.Where((t, i) => i % 2 == 1).ToArray();
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<T> everyOther<T>( IEnumerable<T> 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:
string[] rawarray = new string [] {"Apple","X" .....};
string[] Fruites = new string[rawarray.Length/2+1];
string[] Alphabets = new string[rawarray.Length/2];
For(int i=0; i<rawarray.Length;i++)
{
if(i%2==0)
{
Fruits[i/2]=rawarray[i];
}
else
{
Alphabets[i/2]=rawarray[i];
}
}
Single LINQ:
List<string> list = new List<string>() { "apple", "X", "banana", "Y", "Kiwi", "z" };
var result = list.Select((l, i) => new { l, i })
.GroupBy(p => p.i % 2)
.Select(x => x.Select(v => v.l).ToList())
.ToList();
Then you have a list of lists:
Use the IEnumerable<T>.Where overload which supplies the index.
var fruits = statsname.Where((s, i) => i % 2 == 0).ToArray();
var alphabets = statsname.Where((s, i) => i % 2 != 0).ToArray();