简体   繁体   English

从对象列表中删除重复项 c#

[英]Remove Duplicates from Object List c#

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.以及一个包含大约 4000000 个此类对象的列表。

List<test> list;

How can i remove all duplicates from the list?如何从列表中删除所有重复项? I mean completely identical objects where all values are identical.我的意思是完全相同的对象,其中所有值都相同。

Regards,问候,

Hendrik亨德里克

Use IEquatable<> with linq distinct :将 IEquatable<> 与 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();
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM