Selecting alternate items of an array C#

六月ゝ 毕业季﹏ 提交于 2019-11-28 11:11:23

问题


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 ?


回答1:


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



回答2:


Stolen from How to get Alternate elements using Enumerable in C#

var fruits = myArray.Where((t, i) => i % 2 == 0).ToArray();
var alphabets = myArray.Where((t, i) => i % 2 == 1).ToArray();



回答3:


If i have understood you question correctly what you want is very simple: You want put fruits in array of fruits and same for alphabets and they are appearing alternatively in array statsname so:

for(int i=0,j=0;i<statsname.length;i+2,j++)
    fruits[j]=statsname[i];

for(int i=1,j=0;i<statsname.length;i+2,j++)
    alphabets[j]=statsname[i];



回答4:


Single LINQ:

List<string> list = new List<string>() { "apple", "X", "banana", "Y", "Kiwi", "z" };
var result = list.Select((l, i) => new { l, i })
                 .GroupBy(p => p.i % 2)
                 .Select(x => x.Select(v => v.l).ToList())
                 .ToList();

Then you have a list of lists:




回答5:


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




回答6:


string[] rawarray = new string [] {"Apple","X" .....};
string[] Fruites = new string[rawarray.Length/2+1];
string[] Alphabets = new string[rawarray.Length/2];

For(int i=0; i<rawarray.Length;i++)
{
   if(i%2==0)
   {
     Fruits[i/2]=rawarray[i]; 
   }
   else
   {
     Alphabets[i/2]=rawarray[i]; 
   }   
}



回答7:


using only Arrays:

 var array = new string[] { "apple", "X", "banana", "Y", "Kiwi", "z" };
 var fruit = new string[array.Length];
 var alphabet = new string[array.Length];
 for(var i = 0,j = 0; i < array.Length / 2; i++, j += 2)
 {
     fruit[i] = array[j];               
     alphabet[i] = array[j + 1];
 }



回答8:


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)
  • ...



回答9:


Here is some working code, hopefully this will be helpfull to you:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReadFile
{
    class Program
    {
        static void ReadFile(string filePath, List<string> custumerNames, List<int> phoneNumbers)
        {
            string line = string.Empty;
            var fileStream = new StreamReader(filePath);
            bool isPhoneNumber = true;

            while ((line = fileStream.ReadLine()) != null)
            {
                if (isPhoneNumber)
                {
                    phoneNumbers.Add(Convert.ToInt32(line));
                    isPhoneNumber = false;
                }
                else
                {
                    custumerNames.Add(line);
                    isPhoneNumber = true;
                }
            }

            fileStream.Close();
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Started reading the file...");
            List<string> custumersNamesList = new List<string>();
            List<int> custumersPhonesNumbers = new List<int>();

            ReadFile("SampleFile.txt", custumersNamesList, custumersPhonesNumbers);

            //Assuming both the list's has same lenght.
            for (int i = 0; i < custumersNamesList.Count(); i++)
            {
                Console.WriteLine(string.Format("Custumer Name: {0} , Custumer Phone Number: {1}",
                    custumersNamesList[i], Convert.ToString(custumersPhonesNumbers[i])));
            }

            Console.ReadLine();
        }
    }
}


来源:https://stackoverflow.com/questions/20141241/selecting-alternate-items-of-an-array-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!