I have code that should know that a collection should not be empty or contain only one element.
In general, I want a form extension:
bool collectionHasAtLeast2Items = collection.AtLeast(2);
I can easily write an extension, listing by collection and increasing the indexer until I click on the requested size or exit the elements, but is there something already in the LINQ structure that will do this? My thoughts (in the order that came to me):
bool collectionHasAtLeast2Items = collection.Take(2).Count() == 2; or
bool collectionHasAtLeast2Items = collection.Take(2).ToList().Count == 2;
This would seem to work, although the behavior of taking more elements than the collection contains is not defined (in the documentation) by the Enumerable.Take Method , however, it seems to do what you would expect.
This is not the most efficient solution, listing once to take the elements and then listing them again to count them, which is optional, or listing once to pick the elements, and then creating a list to get the count property, which is n ' t enumerator-y since I really don't want a list.
This is not very good, because I always have to make two statements, first taking βxβ and then checking that I really got βxβ, and this depends on undocumented behavior.
Or maybe I could use:
bool collectionHasAtLeast2Items = collection.ElementAtOrDefault(2) != null;
However, this is not semantically understandable. Maybe it's best to wrap this with a method name, which means what I want. I guess it will be effective, I did not think about the code.
Some other thoughts use Last() , but I clearly don't want to list the entire collection.
Or maybe Skip(2).Any() , again semantically quite obvious, but better than ElementAtOrDefault(2) != null , although I think they give the same result?
Any thoughts?