Using LINQ to Objects to find items in one collection that do not match another

后端 未结 8 1836
清酒与你
清酒与你 2020-12-29 05:04

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

相关标签:
8条回答
  • 2020-12-29 05:59
    var nonmanagers = employees.Select(e => e.Id)
        .Except(managers.Select(m => m.EmployeeId))
        .Select(id => employees.Single(e => e.Id == id));
    
    0 讨论(0)
  • 2020-12-29 06:07
        /// <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.

    0 讨论(0)
提交回复
热议问题