Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure a sequence has a certain length?

Tags:

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?

like image 510
guhou Avatar asked Sep 27 '10 08:09

guhou


People also ask

How can you deal with variable length input sequences?

The most common way people deal with inputs of varying length is padding. You first define the desired sequence length, i.e. the input length you want your model to have. Then any sequences with a shorter length than this are padded either with zeros or with special characters so that they reach the desired length.

How can you deal with variable length input sequences What about variable length output sequences?

The first and simplest way of handling variable length input is to set a special mask value in the dataset, and pad out the length of each input to the standard length with this mask value set for all additional entries created. Then, create a Masking layer in the model, placed ahead of all downstream layers.

What happens when sequence reaches max value?

After an ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum value. NOCYCLE Specify NOCYCLE to indicate that the sequence cannot generate more values after reaching its maximum or minimum value.

What is good sequence?

A good sequence is a sequence of positive integers k = 1,2,... such that the element k occurs before the last occurrence of k + 1. We construct two bijections between the set of good sequences of length n and the set of permutations of length n.


2 Answers

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.

like image 122
Jon Skeet Avatar answered Sep 24 '22 00:09

Jon Skeet


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.

like image 42
Ani Avatar answered Sep 27 '22 00:09

Ani