2014-02-28 64 views
2

你好,我有一個自定義對象的列表(它真的只是一個元組),我試圖從一個列表中刪除同一個對象在另一個列表中。但我很難這樣做。從列表中刪除元組使用linq

下面是代碼:

public class FileNameTuple 
{ 
    public FileNameTuple(string origFileName, string newFileName) 
    { 
     OrigFileName = origFileName; 
     NewFileName = newFileName; 
    } 

    public string OrigFileName 
    { 
     get; 
     set; 
    } 

    public string NewFileName 
    { 
     get; 
     set; 
    } 
} 

     List<FileNameTuple> fileListing = new List<FileNameTuple>(); 
     List<FileNameTuple> failedFileListing = new List<FileNameTuple>(); 

     //doesn't work, has compliation error 
     fileListing.RemoveAll(i => failedFileListing.Contains(i.OrigFileName)); 

回答

2

Contains比較對象本身,要比較的屬性。使用Any

fileListing 
.RemoveAll(i => failedFileListing.Any(fnt => i.OrigFileName == fnt.OrigFileName)); 

如果你想使用Contains你需要重寫Equals(+ GetHashCode):

public class FileNameTuple 
{ 
    //... 
    public override bool Equals(object obj) 
    { 
     if(object.ReferenceEquals(obj, this) return true; 
     FileNameTuple t2 = obj as FileNameTuple; 
     if(t2 == null) return false; 
     return OrigFileName == t2.OrigFileName; 
    } 
    public override int GetHashCode() 
    { 
     return (OrigFileName ?? "").GetHashCode(); 
    } 
} 

現在你可以比較FileNameTuple S:

fileListing.RemoveAll(i => failedFileListing.Contains(i)); 
+0

不錯,這是訣竅,無法包裹我的頭,我需要使用任何。謝謝。 – mgmedick