c# 用对象区分两个列表

标签 c# linq generics

我有这两个列表 resultresultNew:

data.AddMapping<Employee>(x => x.Name, "Name");
data.AddMapping<Employee>(x => x.Code, "Code");
data.AddMapping<Employee>(x => x.WorkingStatus, "Working Status");
var result = (from x in data.Worksheet<Employee>("Tradesmen")
              select x).ToList();


dataNew.AddMapping<Employee>(x => x.Name, "Name");
dataNew.AddMapping<Employee>(x => x.Code, "Code");
dataNew.AddMapping<Employee>(x => x.WorkingStatus, "Working Status");
var resultNew = (from x in dataNew.Worksheet<Employee>("On Leave")
                 select x).ToList();

其中 Employee 是一个简单的 c# 代码,包含 codenameworkingStatus 字段

我想获取 coderesultNew 而不是 result 的数据

我试过这个:

var newEmployees = resultNew.Except(Code = result.Select(s => s.Code)).ToList();

但是我遇到了语法错误:

System.Collections.Generic.List' does not contain a definition for 'Except' and the best extension method overload 'System.Linq.Enumerable.Except(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable)' has some invalid arguments

最佳答案

您可以为新员工的代码创建一个HashSet,然后像这样使用它:

HashSet<string> resultCodes = new HashSet<string>(result.Select(r => r.Code));
List<Employee> newEmployees = resultNew.Where(r => !resultCodes.Contains(r.Code))
                                    .ToList();

您还可以根据属性 Code 为您的类 Employee 覆盖 EqualsGetHashCode ,然后您可以使用 Except喜欢:

class Employee
{
    protected bool Equals(Employee other)
    {
        return string.Equals(Code, other.Code);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((Employee) obj);
    }

    public override int GetHashCode()
    {
        return (Code != null ? Code.GetHashCode() : 0);
    }

    public string Name { get; set; }
    public string Code { get; set; }
    public string WorkingStatus { get; set; }

}

然后:

var newEmployees = resultnew.Except(result).ToList();

请记住,EqualsGetHashCode 的上述实现只考虑了 Code 属性。看这个问题How do you implement GetHashCode for structure with two string, when both strings are interchangeable

关于c# 用对象区分两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25691023/

相关文章:

c# - 如何将两个托管 x86/x64 dll 组合成一个托管 AnyCpu 库?

c# - Linq 谓词查询结果不适用于进一步的 Linq Join

c# - 返回列表中两个变量索引之间的元素

c# - 比较数据集或更好的想法

java - 迁移 Java 类以使用泛型

c# - 如何显示满足所有导入的 UserControl

c# - 比较列表中对象的属性

c# - 根据条件从列表中删除重复项

c# - 不支持约束的通用方法

C# 派生类型到泛型列表作为参数