Selecting alternate items of an array C#

2019-01-29 07:33发布

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 ?

9条回答
疯言疯语
2楼-- · 2019-01-29 08:31
list<string> fruits = new List<string>();
list<string> alphabet = new List<string>();

for (int i = 0; i < array.Length; i++)
{
   if (i % 2 == 0)
       fruits.Add(array[i]);
   else
       alphabet.Add(array[i]);
}

Then you can just do .ToArray on the lists

查看更多
姐就是有狂的资本
3楼-- · 2019-01-29 08:35

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();
查看更多
该账号已被封号
4楼-- · 2019-01-29 08:38

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:

  • skip elements
  • decorate elements
  • change ordering
  • concatenate sequences (see System.Linq.Concat)
  • ...
查看更多
登录 后发表回答