[c#] Any <T>의 반대 방법은 무엇입니까?

컬렉션에 개체가 포함되어 있지 않은지 Linq로 어떻게 확인할 수 있습니까? IE의 반대입니다 Any<T>.

나는 결과를 반전시킬 수 !있지만 가독성을 위해 더 나은 방법이 있는지 궁금했습니다. 확장 프로그램을 직접 추가해야합니까?



답변

None확장 메서드를 쉽게 만들 수 있습니다 .

public static bool None<TSource>(this IEnumerable<TSource> source)
{
    return !source.Any();
}

public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    return !source.Any(predicate);
}


답변

하나 이상의 레코드가 특정 기준과 일치하는지 확인하는 것과 반대되는 것은 모든 레코드가 기준과 일치하지 않는지 확인하는 것입니다.

전체 예제를 게시하지 않았지만 다음과 같은 반대의 경우를 원하면 :

var isJohnFound = MyRecords.Any(x => x.FirstName == "John");

다음을 사용할 수 있습니다.

var isJohnNotFound = MyRecords.All(x => x.FirstName != "John");


답변

추가 된 답변 외에도 Any()메서드 를 래핑하지 않으려면 None()다음과 같이 구현할 수 있습니다 .

public static bool None<TSource>(this IEnumerable<TSource> source)
{
    if (source == null) { throw new ArgumentNullException(nameof(source)); }

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        return !enumerator.MoveNext();
    }
}

public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null) { throw new ArgumentNullException(nameof(source)); }
    if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); }

    foreach (TSource item in source)
    {
        if (predicate(item))
        {
            return false;
        }
    }

    return true;
}

매개 변수가없는 오버로드에 추가로 ICollection<T>LINQ 구현에는 실제로 존재하지 않는 최적화 를 적용 할 수 있습니다 .

ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null) { return collection.Count == 0; }


답변

컬렉션에 하나의 개체가 포함되어 있지 않은지 확인하고 싶지만 컬렉션의 모든 개체가 주어진 기준과 일치 하는지 확인하고 싶지 않을 때이 스레드를 찾았습니다 . 나는 다음과 같은 검사를 끝냈다.

var exists = modifiedCustomers.Any(x => x.Key == item.Key);

if (!exists)
{
    continue;
}


답변