有一个非常简单的类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我创建了这个类的对象列表,包含多个重复项.
所以,我尝试使用Distinct()获取唯一值的列表.
但它不起作用,所以我实施了
IComparable<LinkInformation>
int IComparable<LinkInformation>.CompareTo(LinkInformation other)
{
return this.ToString().CompareTo(other.ToString());
}
Run Code Online (Sandbox Code Playgroud)
然后...
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;
}
Run Code Online (Sandbox Code Playgroud)
使用的代码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();
}
Run Code Online (Sandbox Code Playgroud)
要做什么Distinct()工作?
当你调用它时IEqualityComparer,你需要实际传递你创建的Disctinct.它有两个重载,一个不接受参数,一个接受一个IEqualityComparer.如果您不提供比较器,则使用默认值,并且默认比较器不会比较您希望它们进行比较的对象.
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |