Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 944
Dennis Röttger Avatar asked May 30 '11 11:05

Dennis Röttger


People also ask

What is an anonymous type in C?

Vincent Diamante (CC BY-SA 2.0) An anonymous type is a type that doesn't have a name. You can use an anonymous type to encapsulate a set of read-only properties inside a single unit — and you don't need to define the anonymous type beforehand.

How do you invoke a generic method?

To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular . NET types.

Can you have a generic method in a non generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

What is the difference between an anonymous type and a regular data type C#?

Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.


1 Answers

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");
like image 131
Daniel Hilgarth Avatar answered Sep 30 '22 02:09

Daniel Hilgarth