How to sum all the duplicate numbers in an array with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = { 2, 3, 4, 2, 1, 1, 7, 5, 8, 9, 5, 3, 10, 10 };

        // 2 + 2 + 3 + 3 + 1 + 1 + 5 + 5 + 10 + 10 = 42

        Console.WriteLine(SumUniqueNumbers(arr));
    }

    public static int SumUniqueNumbers(int[] arr) {
        int result = 0;
        HashSet<int> uniqueNumbers = new HashSet<int>();

        foreach (int num in arr) {
            if (arr.Count(x => x == num) > 1) {
                result += num;
            }
        }

        return result;
    }
}


 
/*
run:
   
42
   
*/

 



answered Jun 2, 2024 by avibootz

Related questions

1 answer 102 views
1 answer 103 views
1 answer 107 views
1 answer 127 views
1 answer 94 views
...