Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine whether IEnumerable<T> is a sequence generator or true collection?

Tags:

c#

linq

Let me provide an example:

Suppose i have a method:

public void DoStuff(IEnumerable<T> sequence)
{
    if (/* is lazy sequence */) throw ...

    // Do stuff...
}

And I want to guard against potentially infinite sequences.

Edit:

To elaborate, guarding against infinite collection is only one of the uses. As Jon mentioned. You can easily have infinite IList. Good point.

Other use might be to detect whether data is potentially unrepeatable. Like a random generator. True collection has data already in memory and iterating it twice will give me same data.

like image 528
Kugel Avatar asked Dec 22 '22 07:12

Kugel


2 Answers

There's nothing that's guaranteed, no. You could see whether the sequence also implements IList<T> - that would prohibit iterator block implementations, but could still be a "virtual" list which continues forever, and it would also fail for some other finite non-iterator-block collections.

In terms of what you're trying to protect against, would a 2-billion-long sequence be okay for what you're trying to do? Would an extension method which threw an exception if you ended up with more than some "limit" (but do so lazily) work for you? (Something like Take, but which blew up at the end.)

like image 63
Jon Skeet Avatar answered Dec 23 '22 22:12

Jon Skeet


This is impossible.

The IEnumerable API cannot possibly tell you whether it is infinite or not. You can try casting it to ICollection to catch the common case where someone has passed you one of those, but if that's what you want then why don't you take an ICollection<...> object in the first place?

like image 37
Alastair Maw Avatar answered Dec 23 '22 21:12

Alastair Maw