LINQ: How to declare IEnumerable[AnonymousType]?

You cannot declare IEnumerable<AnonymousType> because the type has no (known) name at build time. So if you want to use this type in a function declaration, make it a normal type. Or just modify your query to return a IENumerable<String> and stick with that type.

Or return IEnumerable<KeyValuePair<Int32, String>> using the following select statement.

select new KeyValuePair<Int32, String>(id, m.Groups[2].Value)

I am not necessarily recommending this... It is a kind of subversion of the type system but you could do this:

1) change your method signature to return IEnumerable (the non generic one)

2) add a cast by example helper:

public static class Extensions{
    public static IEnumerable<T> CastByExample<T>(
            this IEnumerable sequence, 
            T example) where T: class
    {
        foreach (Object o in sequence)
            yield return o as T;
    }
}

3) then call the method something like this:

var example = new { Text = "", ItemId = 0, Path = "" };
foreach (var x in SeachItem(ids).CastByExample(example))
{
    // now you can access the properties of x 
    Console.WriteLine("{0},{1},{2}", x.Text, x.ItemId, x.Path);
}

And you are done.

The key to this is the fact that if you create an anonymous type with the same order, types and property names in two places the types will be reused. Knowing this you can use generics to avoid reflection.

Hope this helps Alex


The method signature on SearchItem indicates that the method returns an IEnumerable<string> but the anonymous type declared in your LINQ query is not of type string. If you want to keep the same method signature, you have to change your query to only select strings. e.g.

return myLine.Select(a => a.Text);

If you insist on returning the data selected by your query, you can return an IEnumerable<object> if you replace your return statement with

return myLine.Cast<object>();

Then you can consume the objects using reflection.

But really, if your going to be consuming an anonymous type outside the method that it is declared in, you should define a class an have the method return an IEnumerable of that class. Anonymous types are convenience but they are subject to abuse.

Tags:

C#

.Net

Linq