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

后端 未结 8 1887
清酒与你
清酒与你 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 06:07

        /// 
        /// This method returns items in a set that are not in 
        /// another set of a different type
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IEnumerable Except(
                                               this IEnumerable items,
                                               IEnumerable other,
                                               Func getItemKey,
                                               Func 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.

提交回复
热议问题