Skip to content

Instantly share code, notes, and snippets.

@OdeToCode
Last active October 20, 2019 14:45
Show Gist options
  • Save OdeToCode/eaf9980a1bed015c287439451a16abde to your computer and use it in GitHub Desktop.
Save OdeToCode/eaf9980a1bed015c287439451a16abde to your computer and use it in GitHub Desktop.
public class Employee
{
public int Id { get; set; }
// ...
}
public class EmployeeComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return x?.Id == y?.Id;
}
public int GetHashCode([DisallowNull] Employee obj)
{
return obj.Id.GetHashCode();
}
}
static void Main(string[] args)
{
var department1 = new [] {
new Employee { Id = 1 },
new Employee { Id = 2 },
new Employee { Id = 3 }
};
var department2 = new [] {
new Employee { Id = 3 },
new Employee { Id = 4 }
};
// will find Employee Id = 3 only if comparer is in place
var duplicates = department1.Intersect(department2, new EmployeeComparer());
// could also use Contains
// var duplicates = department1.Where(e => department2.Contains(e, new EmployeeComparer()));
foreach(var duplicate in duplicates) {
Console.WriteLine( duplicate.Id);
}
}
var languages = new [] { "c#", "javascript", "python "};
var requirements = new [] { "go", "rust", "javascript" };
var union = requirements.Intersect(languages);
// will show: javascript
foreach(var result in union)
{
Console.WriteLine(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment