Anastasie Laurent
Anastasie Laurent

Reputation: 915

c# differenciate two lists with object

I have these two lists result and resultNew:

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

where Employee is a simple c# code that contains code, name and workingStatus fields

I want to take the data which its code is the resultNew and not in the result

I tried this:

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

but I got syntax error:

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

Upvotes: 1

Views: 85

Answers (1)

Habib
Habib

Reputation: 223402

You can create a HashSet for Code of new employees and then use it like:

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

You can also override Equals and GetHashCode for your class Employee base on property Code and then you can use Except like:

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; }

}

and then:

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

Remember the above implementation of Equals and GetHashCode only considers Code property. See this question How do you implement GetHashCode for structure with two string, when both strings are interchangeable

Upvotes: 4

Related Questions