简体   繁体   中英

Lambda Expression “NOT IN” C# 4.0

I create this class for a test. I want to compare to List of the class and get different class between ListA and ListB. In my example the result get only class of ListB.

I do the same thin with list of string and work it

Class Example

public class FileNode
{
    public string Source { get; set; }
    public int Id { get; set; }
}

List<FileNode> ListA = new List<FileNode>
{
    new FileNode{ Id = 1, Source="a" },
    new FileNode{ Id = 2, Source="b" },
};

List<FileNode> ListB = new List<FileNode>
{
    new FileNode{ Id = 1, Source="a" },
    new FileNode{ Id = 2, Source="b" },
    new FileNode{ Id = 3, Source="c" },
};
List<FileNode> ListAB = ListB.Where(m => !ListA.Contains(m)).ToList();

String example, it's works

List<string> a = new List<string> {"a","b","c","d","e" };
List<string> b = new List<string> {"a","b","c","d" };
List<string> ab = a.Where(m => !b.Contains(m)).ToList();

Well Contains is going to call Equals on the elements - and may also use GetHashCode (I doubt it, but you should override it consistently anyway). So you need to override Equals(object) and GetHashCode() in FileNode . (By default, you'll get reference equality.)

Note that as soon as you start trying to use Contains in a query which will execute in the database, it could behave completely different - it wouldn't be looking at your Equals / GetHashCode methods at that point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM