Search code examples
linqremoveall

remove tuple from list using linq


Hello I have a list of a custom object (its really just a tuple), I'm trying to remove from one list where the same object is in another list. But I'm having difficulty doing so.

Here is the code:

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));

Solution

  • Contains compares the object itself, you want to compare a property. Use Any:

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

    If you want to use Contains you need to override 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();
        }
    }
    

    Now you can compare FileNameTuples:

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