How To Combine Two Lists Without Duplicate Values In C#

In this article, we will learn how to combine two lists without duplicate values in C#.

The Union() method is used to combine two lists with distinct values.

Combine int Lists

using System;
using System.Collections.Generic;
using System.Linq;

namespace Combine_Lists
{
    class Program
    {
        static void Main(string[] args)
        {
            var numberList1 = new List<int> { 10, 65, 4, 65, 33, 27, 10, 65 };
            var numberList2 = new List<int> { 1, 2, 3, 4, 3, 5, 5, 6 };
            var result = numberList1.Union(numberList2).ToList();
            result.ForEach(r => Console.WriteLine(r));
        }
    }
}

Output:

Combine string Lists

using System;
using System.Collections.Generic;
using System.Linq;

namespace Combine_Lists
{
    class Program
    {
        static void Main(string[] args)
        {
            var moviesList = new List<string> { "No Time to Die", "Wonder Woman 1984", "Bloodshot", "Black Widow", "Bloodshot" };
            var seriesList = new List<string> { "The Witcher", "Stranger Things", "Game of Thrones", "The Witcher" };
            var result = moviesList.Union(seriesList).ToList();
            result.ForEach(r => Console.WriteLine(r));
        }
    }
}

Output:

Combine Object Lists

Here the list contains objects of a custom class so we need to implement IEquatable, as shown below.

class Student : IEquatable<Student>
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override int GetHashCode()
    {
        return (Name == null ? 0 : Name.GetHashCode()) ^ Age.GetHashCode();
    }
    public bool Equals(Student student)
    {
        return Name.Equals(student.Name) && Age.Equals(student.Age);
    }
}

IEquatable<T> Interface provides an equality check when there is only one way of comparing the objects.

Now, we can use the Union() method same as above.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Combine_Lists
{
    class Program
    {
        static void Main(string[] args)
        {
            var studentList1 = new List<Student>();
            studentList1.Add(new Student { Name = "Steve", Age = 18 });
            studentList1.Add(new Student { Name = "Bill", Age = 25 });
            studentList1.Add(new Student { Name = "Steve", Age = 18 });
            studentList1.Add(new Student { Name = "Lary", Age = 30 });

            var studentList2 = new List<Student>();
            studentList1.Add(new Student { Name = "Steve", Age = 20 });
            studentList1.Add(new Student { Name = "Lary", Age = 42 });
            studentList1.Add(new Student { Name = "Bill", Age = 25 });

            var result = studentList1.Union(studentList2).ToList();
            result.ForEach(r => Console.WriteLine($"Name = {r.Name}, Age = {r.Age}"));
        }
    }
    class Student : IEquatable<Student>
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public override int GetHashCode()
        {
            return (Name == null ? 0 : Name.GetHashCode()) ^ Age.GetHashCode();
        }
        public bool Equals(Student student)
        {
            return Name.Equals(student.Name) && Age.Equals(student.Age);
        }
    }
}

Output:

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check How To Format String As Phone Number In C#

1 Comment

  1. Ivan

    I have something similar to what you describe but with a small difference. For simplicity let’s assume that I have two text files. I have extracted the words (filtered by some criteria, which is not relevant here, etc.) from each of them and put all unique words in two lists of objects (string word, int count). Obviously, some of the words are the same (but with a different word count), and some are unique. I need to combine the two lists the result being adding counts for the duplicate words and/or appending (word, count) for the distinct ones. I implemented it with a foreach loop but it is not very elegant and because of the sheer volume of the texts it is not very efficient. Could you suggest a better solution? Thanks.

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories