I want to find all items in one collection that do not match another collection. The collections are not of the same type, though; I want to write a lambda expression to spe
var nonmanagers = employees.Select(e => e.Id)
.Except(managers.Select(m => m.EmployeeId))
.Select(id => employees.Single(e => e.Id == id));
/// <summary>
/// This method returns items in a set that are not in
/// another set of a different type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TOther"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="items"></param>
/// <param name="other"></param>
/// <param name="getItemKey"></param>
/// <param name="getOtherKey"></param>
/// <returns></returns>
public static IEnumerable<T> Except<T, TOther, TKey>(
this IEnumerable<T> items,
IEnumerable<TOther> other,
Func<T, TKey> getItemKey,
Func<TOther, TKey> getOtherKey)
{
return from item in items
join otherItem in other on getItemKey(item)
equals getOtherKey(otherItem) into tempItems
from temp in tempItems.DefaultIfEmpty()
where ReferenceEquals(null, temp) || temp.Equals(default(TOther))
select item;
}
I don't remember where I found this method.