Predicate methods like TrueForAll() for IEnumberable<T>?

C

cody

Hi! It's great that Arrays and List<T> support functions that use
predicates like TrueForAll(), ConvertAll(), Foreach() and so on.

But why are there no such methods for IEnumerable<T>?
The guidelines say that we should not work with implementations like
List<T> but instead only with interfaces like IList<T> so theoretically
we never could use this handy methods..
 
J

Jon Skeet [C# MVP]

Hi! It's great that Arrays and List<T> support functions that use
predicates like TrueForAll(), ConvertAll(), Foreach() and so on.

But why are there no such methods for IEnumerable<T>?
The guidelines say that we should not work with implementations like
List<T> but instead only with interfaces like IList<T> so theoretically
we never could use this handy methods..

If you defined them in IEnumerable<T> then *every* implementation
would have to provide code to do this - which would be pretty dire.

Instead, use a static method which takes an IEnumerable<T> and a
predicate, and returns true or false. This is exactly what LINQ does -
except that it provides extension methods to make it *look* like the
method is actually provided by IEnumerable<T>.

Jon
 
C

cody

Jon said:
If you defined them in IEnumerable<T> then *every* implementation
would have to provide code to do this - which would be pretty dire.

Instead, use a static method which takes an IEnumerable<T> and a
predicate, and returns true or false. This is exactly what LINQ does -
except that it provides extension methods to make it *look* like the
method is actually provided by IEnumerable<T>.

Jon

Yes that is what I would have suggested, that for all these predicate
helper methods extension methods should be provided, instead of binding
them to a special implementation like List<T> class, although *every*
possible collection should be able to benefit of them.

Who do I have to beat to get this cool stuff included into .NET
framework 4.0 :)

public static class EnumerableExtensions
{
public static bool TrueforAll(this IEnumerable<T> enumerable)
{
..
}

..
}
 
J

Jon Skeet [C# MVP]

cody said:
Yes that is what I would have suggested, that for all these predicate
helper methods extension methods should be provided, instead of binding
them to a special implementation like List<T> class, although *every*
possible collection should be able to benefit of them.

Who do I have to beat to get this cool stuff included into .NET
framework 4.0 :)

Um, you don't - it's all in .NET 3.5.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top