我有这个数组:
string[] words = new string[] {"a","b","c","d","e","f"};
我希望将它分成两个数组,具体取决于索引是偶数还是奇数,如下所示:
string[] odd="a,c,e";
string [] even="b,d,f";
提前致谢
答案 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();