How to sum all the duplicate numbers in an array only once 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 / 2 = 21

        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 (!uniqueNumbers.Contains(num)) {
                if (arr.Count(x => x == num) > 1) {
                    result += num;
                    uniqueNumbers.Add(num);
                }
            }
        }

        return result;
    }
}


 
/*
run:
   
21
   
*/

 



answered Jun 1, 2024 by avibootz
...