Selecting alternate items of an array C#

后端 未结 9 2032
遇见更好的自我
遇见更好的自我 2020-12-22 00:28

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 calle

9条回答
  •  醉梦人生
    2020-12-22 01:04

    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 everyOther( IEnumerable 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)
    • ...

提交回复
热议问题