Search code examples
c#arraysalternate

Selecting alternate items of an array C#


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 called alphabets.

Any simple C# mechanism for it please ?


Solution

  • 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();