views:

1097

answers:

6

I want to check that an IEnumerable contains exactly one element. This snippet does work:

bool hasOneElement = seq.Count() == 1

However it's not very efficient, as Count() will enumerate the entire list. Obviously, knowing a list is empty or contains more than 1 element means it's not empty. Is there an extension method that has this short-circuiting behaviour?

+7  A: 

No, but you can write one yourself:

 public static bool HasExactly<T>(this IEnumerable<T> source, int count)
 {
   if(source == null)
      throw new ArgumentNullException("source");

   if(count < 0)
      return false;

   return source.Take(count + 1).Count() == count;
 }

EDIT: Changed from atleast to exactly after clarification.

For a more general and efficient solution (which uses only 1 enumerator and checks if the sequence implements ICollection or ICollection<T> in which case enumeration is not necessary), you might want to take a look at my answer here, which lets you specify whether you are looking forExact,AtLeast, orAtMost tests.

Ani
don't you still end up enumerating the entire list in that snippet? (due to the `Take` and then `Count`)
BleuM937
@BleuM937: No, `Take` will stream *atleast* the number of items specified but no more.
Ani
I'm not asking for *at least*, I'm asking for *exactly*.
BleuM937
@BleuM937: Edited.
Ani
However, you will double iterate the items won't you? Firstly with the take and then the count. Only the length of items we're interested in, but still twice the number of iterations required.
SamStephens
@SamStephens: Yes, that's right. Which is why a more efficient (but ugly) solution might be more appropriate.
Ani
A: 

I believe what you're looking for is .Single(). Anything other than exactly one will throw InvalidOperationException that you can catch.

http://msdn.microsoft.com/nb-no/library/bb155325.aspx

danijels
I suppose what I'm trying to do could be achieved with this but I don't like throwing exceptions for control flow.
BleuM937
Then use SingleOrDefault() and check if return value is null yourself.
danijels
SingleOrDefault will still will throw an exception if there is more than one item in the list. I don't think this is the way to go, the code with the enumerator should be more efficient.
SamStephens
@SamStephens my bad, I did not take that into account. I agree that throwing/catching exceptions in this case is not the way to go.
danijels
A: 

This is the fastest, but with very bad smell. If you do really really care about the speed(in fact I don't think the Count() operation on a huge IEnumerable<T> will affect the performance a lot!)

public static bool HasExactly<T>(this IEnumerable<T> source, int count)
{
    // check source==null and count is positive
    try  { source.ElementAt(count-1);  }
    catch { return false; }
    try  { source.ElementAt(count);  }
    catch { return true; }
    return true;
}
Danny Chen
-1: IEnumerable<T> doesn't have an indexer
Matt Ellen
@Matt: ops sorry. I've modified it.
Danny Chen
@danny: I've removed my down vote :)
Matt Ellen
@Matt: Thanks. But now since the OP modified his question, this answer doesn't meet his question any more :(
Danny Chen
I'm not convinced it's the fastest, and it will also hide errors which have nothing to do with the length of the sequence. It also starts evaluating the sequence twice, which may not even be feasible in some cases.
Jon Skeet
@Jon: I checked the IL of `ElementAt` and found that it's also using `GetEnumerator` and `MoveNext` to get an item. That is, you are correct. This solution is not fastest, and with bad smell.
Danny Chen
+20  A: 

This should do it:

public static bool ContainsExactlyOneItem<T>(this IEnumerable<T> source)
{
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        // Check we've got at least one item
        if (!iterator.MoveNext())
        {
            return false;
        }
        // Check we've got no more
        return !iterator.MoveNext();
    }
}

You could elide this further, but I don't suggest you do so:

public static bool ContainsExactlyOneItem<T>(this IEnumerable<T> source)
{
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        return iterator.MoveNext() && !iterator.MoveNext();
    }
}

It's the sort of trick which is funky, but probably shouldn't be used in production code. It's just not clear enough. The fact that the side-effect in the LHS of the && operator is required for the RHS to work appropriately is just nasty... while a lot of fun ;)

EDIT: I've just seen that you came up with exactly the same thing but for an arbitrary length. Your final return statement is wrong though - it should be return !en.MoveNext(). Here's a complete method with a nicer name (IMO), argument checking and optimization for ICollection/ICollection<T>:

public static bool CountEquals<T>(this IEnumerable<T> source, int count)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (count < 0)
    {
        throw new ArgumentOutOfRangeException("count",
                                              "count must not be negative");
    }
    // We don't rely on the optimizations in LINQ to Objects here, as
    // they have changed between versions.
    ICollection<T> genericCollection = source as ICollection<T>;
    if (genericCollection != null)
    {
        return genericCollection.Count == count;
    }
    ICollection nonGenericCollection = source as ICollection;
    if (nonGenericCollection != null)
    {
        return nonGenericCollection.Count == count;
    }
    // Okay, we're finally ready to do the actual work...
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        for (int i = 0; i < count; i++)
        {
            if (!iterator.MoveNext())
            {
                return false;
            }
        }
        // Check we've got no more
        return !iterator.MoveNext();
    }
}

EDIT: And now for functional fans, a recursive form of CountEquals (please don't use this, it's only here for giggles):

public static bool CountEquals<T>(this IEnumerable<T> source, int count)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (count < 0)
    {
        throw new ArgumentOutOfRangeException("count", 
                                              "count must not be negative");
    }
    using (IEnumerator<T> iterator = source.GetEnumerator())
    {
        return IteratorCountEquals(iterator, count);
    }
}

private static bool IteratorCountEquals<T>(IEnumerator<T> iterator, int count)
{
    return count == 0 ? !iterator.MoveNext()
        : iterator.MoveNext() && IteratorCountEquals(iterator, count - 1);
}

EDIT: Note that for something like LINQ to SQL, you should use the simple Count() approach - because that'll allow it to be done at the database instead of after fetching actual results.

Jon Skeet
Yes it's ugly, and yes, it's beautiful :-) But no, it's not very obvious when you first see this code.
Philippe Leybaert
LOL @Jon for his `return iterator.MoveNext() `. The answer from me is "both"!
thephpdeveloper
onof
What will happen if you call ContainsExactlyOneItem on a linq-to-sql query? Will the data be fetched from the database?
diamandiev
@diamandiev: Yes. For LINQ to SQL I'd suggest using `Count()` instead, to do it at the database.
Jon Skeet
You can add a test for ICollection, just like Count() does, and skip all the iterating.
Dave Van den Eynde
@Dave: That's true. Will edit to mention it...
Jon Skeet
You need to check `count > 0` in the second part of the recursive function, otherwise you'll count the entire list, not just the relevant part. `(count == 0 ` Also, your parentheses mismatched. And I'd like to emphasize the _please don't use this_ part, since it won't always work - for long iterations it will blow the stack resulting in an uncatchable exception.
configurator
@configurator: Good catch - will edit. In fact, I've decided to use the conditional operator for this bit, as it's probably more appropriate (and closer to what the F# would look like). Of course, in F# I'd hope it would be tail-recursive, avoiding the stack issue. But yes, please don't use it.
Jon Skeet
Bear Monkey
@Bear: Opinion on Twitter has certainly been divided. I think it would at least require a comment, which is always a bit of a warning sign...
Jon Skeet
@Jon No more comments than you 1st version ;)
Bear Monkey
@Bear: Sure... but I wouldn't feel *too* bad about removing the comments in my first version. I think the "smart" version would cause readers to pause for a sufficient length of time to make the "dumb" version better in terms of readability.
Jon Skeet
@Jon, in 3.5 your: "ArgumentOutOfRangeException("count must not be negative")" should read: "ArgumentOutOfRangeException("count", "count must not be negative")" -- I think.
grenade
@grenade: Done.
Jon Skeet
+4  A: 

seq.Skip(1).Any() will tell you if the list has zero or one elements.

I think the edit you made is about the most efficient way to check the length is n. But there's a logic fault, items less than length long will return true. See what I've done to the second return statement.

    public static bool LengthEquals<T>(this IEnumerable<T> en, int length)
    {
        using (var er = en.GetEnumerator())
        {
            for (int i = 0; i < length; i++)
            {
                if (!er.MoveNext())
                    return false;
            }
            return !er.MoveNext();
        }
    }
SamStephens
@SamStephens: Yes, I was just noticing that myself. I prefer your method name, but my variable names :) - actually I've decided I prefer CountEquals after all, as it matches up with the Count() method better :)
Jon Skeet
Yeah, CountEquals sounds right to me, also.
SamStephens
+1  A: 

How about this?

public static bool CountEquals<T>(this IEnumerable<T> source, int count) {
    return source.Take(count + 1).Count() == count;
}

The Take() will make sure we never call MoveNext more than count+1 times.

I'd like to note that for any instance of ICollection, the original implementation source.Count() == count should be faster because Count() is optimised to just look at the Count member.

configurator