Suppose I want to access an object from a Collection
, and I want to be sure
it doesn't iterate through the whole Collection
just to determine the size.
How can I determine and control if a call to Count
results in actually iterating though the collection?
(other than using my own implementation of ICollection
) , in other words are there implementations that offer this?
public void PrintThreeNames(ICollection<string> names)
{
//first I want to know if the collection has at least three elements.
if (names != null && names.Count >= 3)
{
IEnumerator<string> enumerator = names.GetEnumerator();
string value0 = enumerator.Current;
enumerator.MoveNext();
string value1 = enumerator.Current;
enumerator.MoveNext();
string value2 = enumerator.Current;
//print values.
Console.Writeline(value0 + value1 + value2);
}
}
In response to the programmers hero question. I guess I can make a IEnumerable<T>
collection add a million documents to it, and count it to see how fast a call to Count
is as well.
I asked this question as I may choose using IEnumerable
over Collection
, as my collections are so large in numbers and data per item as well, that it will be a problem to return all of them at once.
However, I would like to know the disadvantages of IEnumarable
as well, Joshua pointed about locking it is not a good idea, in another question.