C#: Remove all the values except integer values from a given array of mixed values
C# Sharp Basic: Exercise-91 with Solution
Write a C# Sharp program to remove all values except integer values from a given array of mixed values.
Sample Solution:
C# Sharp Code:
using System;
using System.Linq;
namespace exercises
{
class Program
{
static void Main(string[] args)
{
// Initializing an array of objects with various types of values
object[] mixedArray = new object[6];
mixedArray[0] = 25;
mixedArray[1] = "Anna";
mixedArray[2] = false;
mixedArray[3] = System.DateTime.Now;
mixedArray[4] = -112;
mixedArray[5] = -34.67;
// Displaying the original elements of the mixed array
Console.WriteLine("Original array elements:");
for (int i = 0; i < mixedArray.Length; i++)
{
Console.Write(mixedArray[i] + " ");
}
// Calling the 'test' method to extract integer values from the mixed array
int[] new_nums = test(mixedArray);
// Displaying the integer values extracted from the mixed array
Console.WriteLine("\n\nAfter removing all the values except integer values from the said array of mixed values:");
for (int i = 0; i < new_nums.Length; i++)
{
Console.Write(new_nums[i] + " ");
}
}
// Method to extract integer values from an array of objects
public static int[] test(object[] nums)
{
// Using LINQ's 'OfType' to filter and convert objects to integers and returning as an array
return nums.OfType<int>().ToArray();
}
}
}
Sample Output:
Original array elements: 25 Anna False 4/24/2021 11:43:11 AM -112 -34.67 After removing all the values except integer values from the said array of mixed values: 25 -112
Flowchart:
C# Sharp Code Editor:
Previous: Write a C# Sharp program to count number of ones and zeros in the binary representation of a given integer.
Next: Write a C# Sharp program to find the next prime number of a given number. If the given number is a prime number, return the number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/csharp-exercises/basic/csharp-basic-exercise-91.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics