Pass a lambda expression in place of IComparer or IEqualityComparer or any single-method interface?

后端 未结 8 1975
闹比i
闹比i 2020-12-08 08:57

I happened to have seen some code where this guy passed a lambda expression to a ArrayList.Sort(IComparer here) or a IEnumerable.SequenceEqual(IEnumerable list, IEqualityCom

8条回答
  •  情话喂你
    2020-12-08 09:31

    In case if you need this function for use with lambda and possibly two different element types:

    static class IEnumerableExtensions
    {
        public static bool SequenceEqual(this IEnumerable first, IEnumerable second, Func comparer)
        {
            if (first == null)
                throw new NullReferenceException("first");
    
            if (second == null)
                throw new NullReferenceException("second");
    
            using (IEnumerator e1 = first.GetEnumerator())
            using (IEnumerator e2 = second.GetEnumerator())
            {
                while (e1.MoveNext())
                {
                    if (!(e2.MoveNext() && comparer(e1.Current, e2.Current)))
                        return false;
                }
    
                if (e2.MoveNext())
                    return false;
            }
    
            return true;
        }
    }
    

提交回复
热议问题