【问题标题】:Lambda Expression "NOT IN" C# 4.0Lambda 表达式“不在”C# 4.0
【发布时间】:2013-01-22 21:36:17
【问题描述】:

我为测试创建了这个类。 我想与类的列表进行比较,并在 ListA 和 ListB 之间获得不同的类。在我的示例中,结果仅获得 ListB 类。

我对字符串列表做同样的细化处理

类示例

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

字符串示例,有效

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

【问题讨论】:

标签: linq entity-framework c#-4.0


【解决方案1】:

Contains 将在元素上调用 Equals - 并且也可能使用 GetHashCode(我对此表示怀疑,但无论如何你应该始终覆盖它)。所以你需要覆盖FileNode中的Equals(object)GetHashCode()。 (默认情况下,您将获得引用相等性。)

请注意,一旦您开始尝试在将在数据库中执行的查询中使用 Contains,它的行为可能会完全不同 - 它不会查看您的 Equals/GetHashCode 方法点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2015-12-23
    • 2011-01-26
    • 2020-07-02
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多