Distinct()如何在对象列表中查找唯一元素 [英] Distinct() How to find unique elements in list of objects

查看:80
本文介绍了Distinct()如何在对象列表中查找唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个非常简单的类:

public class LinkInformation
{
    public LinkInformation(string link, string text, string group)
    {
        this.Link = link;
        this.Text = text;
        this.Group = group;
    }

    public string Link { get; set; }
    public string Text { get; set; }
    public string Group { get; set; }

    public override string ToString()
    {
        return Link.PadRight(70) + Text.PadRight(40) + Group;
    }
}

然后我创建一个此类的对象列表,其中包含多个重复项.

And I create a list of objects of this class, containing multiple duplicates.

因此,我尝试使用 Distinct()来获取唯一值列表.

So, I tried using Distinct() to get a list of unique values.

但是它不起作用,所以我实现了

But it does not work, so I implemented

IComparable<LinkInformation>

    int IComparable<LinkInformation>.CompareTo(LinkInformation other)
    {
        return this.ToString().CompareTo(other.ToString());
    }

然后...

IEqualityComparer<LinkInformation>

    public bool Equals(LinkInformation x, LinkInformation y)
    {
        return x.ToString().CompareTo(y.ToString()) == 0;
    }

    public int GetHashCode(LinkInformation obj)
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + obj.Link.GetHashCode();
        hash = hash * 23 + obj.Text.GetHashCode();
        hash = hash * 23 + obj.Group.GetHashCode();
        return hash;
    }

使用 Distinct 的代码为:

    static void Main(string[] args)
    {
        string[] filePath = {   @"C:\temp\html\1.html",
                                @"C:\temp\html\2.html",
                                @"C:\temp\html\3.html",
                                @"C:\temp\html\4.html",
                                @"C:\temp\html\5.html"};

        int index = 0;

        foreach (var path in filePath)
        {
            var parser = new HtmlParser();

            var list = parser.Parse(path);

            var unique = list.Distinct();

            foreach (var elem in unique)
            {
                var full = new FileInfo(path).Name;
                var file = full.Substring(0, full.Length - 5);
                Console.WriteLine((++index).ToString().PadRight(5) + file.PadRight(20) + elem);
            }
        }

        Console.ReadKey();
    }

要使 Distinct()工作必须做什么?

推荐答案

调用它时,您实际上需要将您创建的 IEqualityComparer 传递给 Disctinct .它有两个重载,一个重载不接受参数,另一个重载 IEqualityComparer .如果您不提供比较器,则使用默认值,并且默认比较器不会按照您希望比较的对象进行比较.

You need to actually pass the IEqualityComparer that you've created to Disctinct when you call it. It has two overloads, one accepting no parameters and one accepting an IEqualityComparer. If you don't provide a comparer the default is used, and the default comparer doesn't compare the objects as you want them to be compared.

这篇关于Distinct()如何在对象列表中查找唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆