我有一個自定義結構和重載linq的除去方法刪除重複項的問題。重載Linq除了允許自定義結構與字節數組
我的結構如下:
public struct hashedFile
{
string _fileString;
byte[] _fileHash;
public hashedFile(string fileString, byte[] fileHash)
{
this._fileString = fileString;
this._fileHash = fileHash;
}
public string FileString { get { return _fileString; } }
public byte[] FileHash { get { return _fileHash; } }
}
現在,下面的代碼工作正常:
public static void test2()
{
List<hashedFile> list1 = new List<hashedFile>();
List<hashedFile> list2 = new List<hashedFile>();
hashedFile one = new hashedFile("test1", BitConverter.GetBytes(1));
hashedFile two = new hashedFile("test2", BitConverter.GetBytes(2));
hashedFile three = new hashedFile("test3", BitConverter.GetBytes(3));
hashedFile threeA = new hashedFile("test3", BitConverter.GetBytes(4));
hashedFile four = new hashedFile("test4", BitConverter.GetBytes(4));
list1.Add(one);
list1.Add(two);
list1.Add(threeA);
list1.Add(four);
list2.Add(one);
list2.Add(two);
list2.Add(three);
List<hashedFile> diff = list1.Except(list2).ToList();
foreach (hashedFile h in diff)
{
MessageBox.Show(h.FileString + Environment.NewLine + h.FileHash[0].ToString("x2"));
}
}
此代碼顯示 「threeA」 和 「四有」 就好了。但是,如果我做了以下。
public static List<hashedFile> list1(var stuff1)
{
//Generate a List here and return it
}
public static List<hashedFile> list2(var stuff2)
{
//Generate a List here and return it
}
List<hashedFile> diff = list1.except(list2);
「diff」變成「list1」的精確副本。我還應該提到,我正在從System.Security.Cryptography.MD5中將ComputeHash的字節數組發送到列表中的字節文件哈希。
有關如何重載Except的Except或GetHashCode方法的任何想法,以成功地從列表2中排除重複的值?
我真的很感激它!謝謝! 〜MrFreeman
編輯:這是我最初是如何試圖用List<hashedFile> diff = newList.Except(oldList, new hashedFileComparer()).ToList();
class hashedFileComparer : IEqualityComparer<hashedFile>
{
public bool Equals(hashedFile x, hashedFile y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.FileString == y.FileString && x.FileHash == y.FileHash;
}
public int GetHashCode(hashedFile Hashedfile)
{
if (Object.ReferenceEquals(Hashedfile, null)) return 0;
int hashFileString = Hashedfile.FileString == null ? 0 : Hashedfile.FileString.GetHashCode();
int hashFileHash = Hashedfile.FileHash.GetHashCode();
int returnVal = hashFileString^hashFileHash;
if (Hashedfile.FileString.Contains("blankmusic") == true)
{
Console.WriteLine(returnVal.ToString());
}
return returnVal;
}
}
採取的字節數組散列碼功能。如果上面的'HashedFile'類型的代碼就是所有你需要比行爲是正常的,因爲沒有'Equal' /'GetHashCode'(因爲數組和其他.NET集合一個沒有被比較的價值 - 所以你需要自己寫)。注意:當你想要一些痛苦時,使用'struct'往往是個人選擇,一定要明白你在做什麼。 –
我重載了我自己的IEqualityComparer,但它產生完全相同的結果。實際上,單步執行代碼時,甚至在使用Except方法時甚至不會觸及重載的「Equals」。 –
MrFreeman
爲什麼'HashedFile'是一個結構? –