-1

What is the simplest way to get generic IEnumerable<T> from System.Collections.IEnumerable (which contains only T type elements) ?

Something say to me that there should be simple (avoiding LINQ) standard wrapper, but I can't find it.

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
  • I don't understand your question, can you be more clear? – Marco Salerno Mar 19 '17 at 19:17
  • 1
    Use OfType or Cast extensions. – Evk Mar 19 '17 at 19:17
  • Most likely you are seeking the `Cast` method, but it's considered LINQ (defined in `Enumerable` class). If you are sure it contains only `T` type elements, you can use simple C# cast, e.g. `(IEnumerable)enumerable` – Ivan Stoev Mar 19 '17 at 19:18
  • @IvanStoev simple cast will only work if underlying type _also_ implements `IEnumerable`. For example `static IEnumerable Test() { yield return 1;yield return 2;}` contains only elements of type `int` but cannot be casted to `IEnumerable`. – Evk Mar 19 '17 at 19:31
  • @MarcoSalerno instead of "avoiding Linq" I want to say avoid "Linq.Expression". In my imagination every System.Linq functionality had Expression parsing inside :) what was overklill for such task, but now I see that it is false. Cast doesn't contain Expression and is what I need. – Roman Pokrovskij Mar 19 '17 at 20:51
  • @Evk Ok, ok, same for `ArrayList`, `HashTable` etc., of course `Cast` is the right way. – Ivan Stoev Mar 20 '17 at 12:30

1 Answers1

1

Simplest and shortest is with LINQ. You can enumerate it without LINQ:

foreach (T item in IEnumerableCollection)

and this is pretty much what .Cast<T>() does:

static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
    foreach (object obj in source) yield return (TResult)obj;
}
Slai
  • 22,144
  • 5
  • 45
  • 53