Удалить дубликаты из списка объектов c# - PullRequest
0 голосов
/ 17 марта 2020

У меня есть список объектов, объект выглядит следующим образом:

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

и список, содержащий около 4000000 объектов этого типа.

List<test> list;

Как удалить все дубликаты из списка? Я имею в виду полностью идентичные объекты, где все значения идентичны.

С уважением,

Хендрик

1 Ответ

1 голос
/ 17 марта 2020

Используйте IEquatable <> с отличным linq:

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();
        }
    }

}
...