I'm going to divide what's in an array in C# into two arrays.

Asked 2 years ago, Updated 2 years ago, 40 views

string[] num = {"1"",2"",3"",4"",5"",6"}; // this array is used to display

You want to divide it into two arrays:
How do I divide an array into two arrays?
string[] odd = {"1","3","5"};

string[] even = {"2","4","5"};

c#

2022-09-22 21:15

1 Answers

Try using LINQ of C#.

using System.LINQ;
// ...

var odd = num.Where(str => (Int32.Parse(str)%2)==1);
var even = num.Where(str => (Int32.Parse(str)%2)==0);

Reference link

[1] https://www.dotnetperls.com/linq

Code Execution Example

using System;
using System.Linq;
public class Hello1 {
    public static void Main() {
        string[] num = {"1","2","3","4","5","6"}; 
        var odd = num.Where(str => (Int32.Parse(str)%2)==1);
        Console.WriteLine("ODD");
        foreach (string value in odd)
        {
            Console.WriteLine(value);
        }        
        var even = num.Where(str => (Int32.Parse(str)%2)==0);
        Console.WriteLine("EVEN");
        foreach (string value in even)
        {
            Console.WriteLine(value);
        }        
    }
}


2022-09-22 21:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.