代表奇数或偶数将字符串拆分为两个数组

时间:2015-03-23 08:58:51

标签: c#

我有这个数组:

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

我希望将它分成两个数组,具体取决于索引是偶数还是奇数,如下所示:

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

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以将Enumerable.Where的重载与索引和余数%一起使用:

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

使用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();

答案 1 :(得分:1)

 var odd = words.Where(item =>Array.IndexOf(words,item) % 2 ==1).ToArray();
 var even = words.Where(item =>Array.IndexOf(words,item) % 2 ==0).ToArray();