开发者

Call Generic Method with an anonymous Type (C#)

开发者 https://www.devze.com 2023-03-09 10:32 出处:网络
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

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 w开发者_C百科hat 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");
0

精彩评论

暂无评论...
验证码 换一张
取 消