array={“riya”,“diya”,45,23} i want to add only digit in c#. how can i add any one can help me please.
hey i tried but not resolved.
Then try this approach
array = {“riya”, “diya”, 45, 23}
sumOfDigits = 0
For Each item In array
If Char.IsDigit(item.ToString.Chars(0)) Then
sumOfDigits = sumOfDigits + Convert.ToInt32(item)
End If
Next
Log Message: "Sum of digits: " + sumOfDigits.ToString
Can you try this code:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
object[] array = { "riya", "diya", 45, 23 };
List<int> digits = new List<int>();
foreach (var item in array)
{
if (item is int)
{
digits.Add((int)item);
}
else if (item is string)
{
string str = (string)item;
foreach (char c in str)
{
if (char.IsDigit(c))
{
digits.Add(int.Parse(c.ToString()));
}
}
}
}
// Now digits list contains all the digits found in the array
int sum = 0;
foreach (int digit in digits)
{
sum += digit;
}
// Print the sum of all the digits
Console.WriteLine("Sum of all digits: " + sum);
}
}
Output:
Hope it helps!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
object[] array = { "riya", "diya", 45, 23 };
int sum = array.OfType<int>().Sum();
Console.WriteLine($"The sum of all integers in the array is: {sum}");
}
}
}

please explain this below line
int sum = array.OfType().Sum();
@Madhuri_kushwaha1
array.OfType<int>()- this is LINQ method filters the array elements, returning int. This part of the code filters the elements of array to include only those that are of the type int . The OfType<T>() method is a generic method that returns an IEnumerable<T> containing all the elements in the original collection that can be cast to the specified type T.
" Filters the elements of an IEnumerable based on a specified type."
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.

