使用linq从列表中删除元组

时间:2014-02-28 15:49:46

标签: linq removeall

你好我有一个自定义对象的列表(它实际上只是一个元组),我试图从一个列表中删除同一个对象在另一个列表中。但是我很难这样做。

以下是代码:

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 个答案:

答案 0 :(得分: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));

答案 1 :(得分:0)

如果您只想要一个已过滤的列表而不是更改现有列表,则可以使用Except LINQ operator

如果您无法更改Tim Schmelter类,并且不想构建自定义equality comparer,则可以随时使用我的PredicateEqualityComparer

fileListing.Except(
    failedFileListing,
    new PredicateEqualityComparer((f1, f2) => f1.OriginalName == f2.OriginalName));