0

i have a Object List, the object look like the following:

class test{
string a {get;set}
string b {get;set}
string c {get;set}
string d {get;set}
string e {get;set}
}

and a list containing about 4000000 Objects of this type.

List<test> list;

How can i remove all duplicates from the list? I mean completely identical objects where all values are identical.

Regards,

Hendrik

Hendriks91
  • 81
  • 5
  • 1
    Does this answer your question? [Remove duplicates from list of object](https://stackoverflow.com/questions/42069841/remove-duplicates-from-list-of-object) [This](https://stackoverflow.com/questions/45716645/remove-duplicate-item-from-list) and [this](https://stackoverflow.com/questions/30434426/how-to-remove-duplicates-from-a-list-of-custom-objects-by-a-property-of-the-obj) also almost the same duplicates. Implementing `Equals` and `GetHashCode`, then `GroupBy` or `Distinct` will solve the problem – Pavel Anikhouski Mar 17 '20 at 19:40

1 Answers1

1

Use IEquatable<> with linq distinct :

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> items = new List<Test>() {
                new Test() { a = "1", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "1", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "1", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "2", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "3", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "4", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "5", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "6", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "7", b = "2", c = "3", d = "4", e = "5"},
                new Test() { a = "8", b = "2", c = "3", d = "4", e = "5"}
            };

            List<Test> distinct = items.Distinct().ToList();
        }
    }
    public class Test : IEquatable<Test>
    {
        public string a { get; set; }
        public string b { get; set; }
        public string c { get; set; }
        public string d { get; set; }
        public string e { get; set; }

        public Boolean Equals(Test other)
        {
            return
                (this.a == other.a) &&
                (this.b == other.b) &&
                (this.c == other.c) &&
                (this.d == other.d) &&
                (this.e == other.e);
        }
        public override int GetHashCode()
        {
            return (this.a + "^" + this.b + "^" + this.c + "^" + this.d + "^" + this.e).GetHashCode();
        }
    }

}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Hello jdweng, i tryed to modify my source Code but still get the Full List with the duplicates as result :( – Hendriks91 Mar 18 '20 at 10:32