how does except method work in linq

后端 未结 5 2193
梦毁少年i
梦毁少年i 2020-12-05 20:45

I have the classes:

class SomeClass
{
   public string Name{get;set;}
   public int SomeInt{get;set;}
}


class SomeComparison: IEqualityComparer

        
5条回答
  •  清歌不尽
    2020-12-05 20:53

    It seems to me this would be more efficient

    private static IEnumerable ExceptImpl(
        IEnumerable first,
        IEnumerable second,
        IEqualityComparer comparer)
    {
        HashSet bannedElements = new HashSet(second, comparer);
        foreach (TSource item in first)
        {
            if (!bannedElements.Contains(item))
            {
                yield return item;
            }
        }
    }
    

    Contains is O(1)

    Add is if Count is less than the capacity of the internal array, this method is an O(1) operation. If the HashSet object must be resized, this method becomes an O(n) operation, where n is Count.

提交回复
热议问题