我有一個List
存儲在我的電腦上的文件路徑。我的目標是首先篩選出具有相同名稱的文件,然後篩選出具有相同大小的文件。
爲此,我做了兩類實施IEqualityComparer<string>
,並實施了Equals
和GetHashCode
的方法。IEqualityComparer不按預期工作
var query = FilesList.Distinct(new CustomTextComparer())
.Distinct(new CustomSizeComparer());
兩個類的代碼如下: -
public class CustomTextComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (Path.GetFileName(x) == Path.GetFileName(y))
{
return true;
}
return false;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
public class CustomSizeComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
if (new FileInfo(x).Length == new FileInfo(y).Length)
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
但代碼不能正常工作。
它不會拋出任何異常,也沒有任何編譯器錯誤,但問題是代碼不起作用(不排除重複的文件)。
那麼,我該如何糾正這個問題呢?有什麼我可以做的,使代碼正常工作。
你標題並不反映問題的內容。請閱讀[我如何寫一個好的標題?](http://meta.stackexchange。com/questions/10647/how-do-i-write-a-good-title) –