Dennis Röttger
Dennis Röttger

Reputation: 1985

Call Generic Method with an anonymous Type (C#)

Let's just say I'd like to iterate over a string[][], append a value using an anonymous type and perform a generic ForEach-Extensionmethod on the result (brilliant example, I know, but I suppose you'll get the jist of it!).

Here's my code:

//attrs = some string[][]
attrs.Select(item => new { name = HttpContext.GetGlobalResourceObject("Global", item[0].Remove(0, 7)), value = item[1] })
            .ForEach</*????*/>(/*do stuff*/);

What exactly would I put in the Type-Parameter of ForEach?

Here's what ForEach looks like:

public static void ForEach<T>(this IEnumerable<T> collection, Action<T> act)
{
    IEnumerator<T> enumerator = collection.GetEnumerator();
    while (enumerator.MoveNext())
        act(enumerator.Current);
}

Upvotes: 5

Views: 931

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

You don't need to specify the type explicitly, because it can be inferred from the supplied parameters:

attrs.Select(item => new 
                     { 
                         name = HttpContext.GetGlobalResourceObject("Global", 
                                                      item[0].Remove(0, 7)), 
                         value = item[1] 
                     })
     .ForEach(x => x.name = "something");

Upvotes: 8

Related Questions