开发者

Alternate way to use linq to determine if an element does not exist in a collection?

I use:

if (!ObjectCollection.Any(o => o.Property == SomeValue))
    // ...

or:

if (!IntCollection.Contains(42))
    // ...

to determine if a collection does not have a particular element, but some people miss the ! negation and misinterpre开发者_开发知识库t.

Is there another way to determine that a collection does not contain a particular element that doesn't use the negation operator? I prefer to stick to dot notation instead of query expression, but maybe a query expression is more readable to someone who misses the bang.


There's nothing in standard LINQ, but if you really don't like using ! (which is the approach I'd recommend) you could always write your own extension methods:

public static bool DoesNotContain<T>(this IEnumerable<T> source, T item)
{
    return !source.Contains(item);
}


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

(You can use these for things like LINQ to SQL as well if you're just using them as the final call - you wouldn't be able to use them in nested queries though, as the query translator wouldn't understand them.)


I understand your concern about readability for the ! operator. Two common solutions I've used:

A) Put spaces around the ! so that it stands out and is easier to see a la

if ( ! IntCollection.Contains(42) )
    // ... the ! stands out

B) Write a readability extension method that makes it nicer

public static class Readability
{
    public static bool Missing<T>(this Enumerable<T> source, T value)
    {
        return ! source.Contains(value);
    }
}


My suggestion is replace ! with == false

if (ObjectCollection.Any(o => o.Property == SomeValue) == false)
    // ...

And

if (IntCollection.Contains(42) == false)
    // ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜