c#使用object区分两个列表

时间:2014-09-05 17:24:27

标签: 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是包含codenameworkingStatus字段的简单c#代码

我想获取coderesultNew而不是result

的数据

我试过了:

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

但我遇到语法错误:

  

System.Collections.Generic.List'不包含'Except'的定义和最佳扩展方法重载'System.Linq.Enumerable.Except(System.Collections.Generic.IEnumerable,System.Collections.Generic.IEnumerable) )'有一些无效的论点

1 个答案:

答案 0 :(得分:4)

您可以为新员工代码创建HashSet,然后将其用作:

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

您还可以在属性Equals上覆盖您的类Employee的GetHashCodeCode,然后您可以使用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