Selecting alternate items of an array C#

后端 未结 9 2034
遇见更好的自我
遇见更好的自我 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条回答
  • 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];
    
    0 讨论(0)
  • 2020-12-22 01:23

    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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-22 01:25
    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

    0 讨论(0)
提交回复
热议问题