score:148

Accepted answer

you can use cast<t>() or oftype<t> to get a generic version of an ienumerable that fully supports linq.

eg.

ienumerable objects = ...;
ienumerable<string> strings = objects.cast<string>();

or if you don't know what type it contains you can always do:

ienumerable<object> e = objects.cast<object>();

if your non-generic ienumerable contains objects of various types and you are only interested in eg. the strings you can do:

ienumerable<string> strings = objects.oftype<string>();

score:4

you can also use linq's query comprehension syntax, which casts to the type of the range variable (item in this example) if a type is specified:

ienumerable list = new arraylist { "dog", "cat" };

ienumerable<string> result =
  from string item in list
  select item;

foreach (string s in result)
{
    // invalidcastexception at runtime if element is not a string

    console.writeline(s);
}

the effect is identical to @jaredpar's solution; see 7.16.2.2: explicit range variable types in the c# language specification for details.

score:13

yes it can. you just need to use the cast<t> function to get it converted to a typed ienumerable<t>. for example:

ienumerable e = ...;
ienumerable<object> e2 = e.cast<object>();

now e2 is an ienumerable<t> and can work with all linq functions.


Related Query

More Query from same tag