문제

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));
도움이 되었습니까?

해결책

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

다른 팁

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top