Question

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));
Was it helpful?

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

OTHER TIPS

If you just want a filtered list instead of changing an existing list, you can use the Except LINQ operator.

If you can't change your class like Tim Schmelter and don't want to build a custom equality comparer, you can always use my PredicateEqualityComparer.

fileListing.Except(
    failedFileListing,
    new PredicateEqualityComparer((f1, f2) => f1.OriginalName == f2.OriginalName));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top