Skip to content

Instantly share code, notes, and snippets.

@Strelok78
Last active April 25, 2025 12:27
Show Gist options
  • Save Strelok78/1a2b428f4b281600a46de7030e12736e to your computer and use it in GitHub Desktop.
Save Strelok78/1a2b428f4b281600a46de7030e12736e to your computer and use it in GitHub Desktop.
Concat two string arrays into one collection without duplicates
using System.Collections;
using System.Diagnostics;
using System.Text;
namespace iJuniorPractice;
class Program
{
static void Main(string[] args)
{
string[] arrayOne = { "1", "2", "4" };
string[] arrayTwo = { "1", "2", "6", "8" };
List<int> result = new List<int>();
StringArrayToIntList(result, arrayOne);
StringArrayToIntList(result, arrayTwo);
WriteListObjects(result);
}
static void StringArrayToIntList(List<int> list, string[] array)
{
foreach (var value in array)
{
if(int.TryParse(value, out int number) && list.Contains(number) == false)
list.Add(number);
}
}
static void WriteListObjects(List<int> numbersList)
{
foreach (var value in numbersList)
{
Console.Write(value);
}
}
}
@Strelok78
Copy link
Author

Strelok78 commented Apr 25, 2025

solution via HashSet:

namespace iJuniorPractice;

class Program
{

static void Main(string[] args)
    {
        string[] arrayOne = { "1", "2", "4" };
        string[] arrayTwo = { "1", "2", "6", "8" };
        
        HashSet<int> result = GetUniqueHashSet(ParseToIntList(arrayOne), ParseToIntList(arrayTwo));
        WriteHashObjects(result);
    }

static List<int> ParseToIntList(string[] array)
    {
        List<int> result = new List<int>();

        foreach (var value in array)
        {
            if(int.TryParse(value, out int number))
                result.Add(number);
        }

        return result;
    }

static void WriteHashObjects(HashSet<int> numbersList)
    {
        foreach (var value in numbersList)
        {
            Console.Write(value);
        }
    }

static HashSet<int> GetUniqueHashSet(List<int> listOne, List<int> listTwo)
    {
        HashSet<int> uniqueList = new HashSet<int>();

        FillHashSetByList(listOne, uniqueList);
        FillHashSetByList(listTwo, uniqueList);

        return uniqueList;
    }

static void FillHashSetByList(List<int> listTwo, HashSet<int> uniqueList)
    {
        foreach (var number in listTwo)
        {
            uniqueList.Add(number);
        }
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment