Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have this array:

 string[] words = new string[] {"a","b","c","d","e","f"};

I want to split it in two arrays depending if the index is even or odd, like this:

string[] odd="a,c,e";
string [] even="b,d,f";

thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
402 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the overload of Enumerable.Where with the index and the remainder %:

string[] even =  words.Where((str, ix) => ix % 2 == 0).ToArray();
string[]  odd =  words.Where((str, ix) => ix % 2 == 1).ToArray();

Another way using ToLookup:

var evenOddIndexLookup = words.Select((str, index) => new { str, index }).ToLookup(x => x.index % 2);
string[] even = evenOddIndexLookup[0].Select(x => x.str).ToArray();
string[]  odd = evenOddIndexLookup[1].Select(x => x.str).ToArray();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...