简体   繁体   中英

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);
}

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM